Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p><strong>Edit:</strong> @Dwin's comment to the Q was a bit cryptic, and seeing as my first attempt at part 1 of the Q was not correct due to the unclear Q, I'll try to redeem myself with a go at expanding on DWin's comment:</p> <p>[Assuming <code>dat</code> contains the data you quote in the Q.] First, merge <code>dat</code> with itself:</p> <pre><code>&gt; foo &lt;- merge(dat[, -4], dat, by.x = "Date", by.y = "Date") &gt; head(foo) Date Name.x Price.x Name.y Price.y Interest 1 01.02.10 X 120 X 120 0.2 2 01.02.10 X 120 R 120 0.2 3 01.02.10 X 120 X 130 0.2 4 01.02.10 X 120 X 140 0.2 5 01.02.10 X 120 R 130 0.2 6 01.02.10 R 120 X 120 0.2 </code></pre> <p>Next, get out the rows where <code>Price.x == Price.y</code> <strong>and</strong> where <code>Name.x != Name.y</code></p> <pre><code>&gt; (foo &lt;- foo[with(foo, which(Price.x == Price.y &amp; Name.x != Name.y)),]) Date Name.x Price.x Name.y Price.y Interest 2 01.02.10 X 120 R 120 0.2 6 01.02.10 R 120 X 120 0.2 15 01.02.10 X 130 R 130 0.2 23 01.02.10 R 130 X 130 0.2 </code></pre> <p>Then, get rid of the superfluous columns:</p> <pre><code>&gt; (foo &lt;- foo[, -(4:5)]) Date Name.x Price.x Interest 2 01.02.10 X 120 0.2 6 01.02.10 R 120 0.2 15 01.02.10 X 130 0.2 23 01.02.10 R 130 0.2 </code></pre> <p>And finally, fix-up the column names:</p> <pre><code>&gt; names(foo) &lt;- names(dat) &gt; foo Date Name Price Interest 2 01.02.10 X 120 0.2 6 01.02.10 R 120 0.2 15 01.02.10 X 130 0.2 23 01.02.10 R 130 0.2 </code></pre> <hr> <p>The second thing can be done using <code>ifelse</code></p> <pre><code>with(dat, ifelse(Name == "X", Price + 100*Interest, Price)) </code></pre> <p>Which gives something this</p> <pre><code>&gt; with(dat, ifelse(Name == "X", Price + 100*Interest, Price)) [1] 140 120 150 160 130 </code></pre> <p>The reason that the <code>if()</code> doesn't work, is that <code>if()</code> only take a scalar logical (a single <code>TRUE</code> or <code>FALSE</code>), yet <code>Name == "X"</code> returns a logical vector:</p> <pre><code>&gt; with(dat, Name == "X") [1] TRUE FALSE TRUE TRUE FALSE </code></pre> <p>In these cases, <code>ifelse()</code> is your friend.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload