Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>There's a lot that needs explaining here. Let's start with the simplest case. In your first example, all you need is:</p> <pre><code>mydf$z &lt;- with(mydf,ifelse(x == 1,0,n)) </code></pre> <p>An equivalent <code>ddply</code> solution might look like this:</p> <pre><code>ddply(mydf,.(x),transform,z = ifelse(x == 1,0,n)) </code></pre> <p>Probably your biggest source of confusion is that you seem to not understand what is being passed as arguments to functions within <code>ddply</code>.</p> <p>Consider your first attempt:</p> <pre><code>k &lt;- function(x) { mydf$z &lt;- ifelse(x == 1, 0, mydf$n) return (mydf) } </code></pre> <p>The way <code>ddply</code> works is that it splits <code>mydf</code> up into several, smaller data frame, based on the values in the column <code>x</code>. That means that each time <code>ddply</code> calls <code>k</code>, the argument passed to <code>k</code> is <em>a data frame</em>. Specifically, a subset of you primary data frame.</p> <p>So within <code>k</code>, <code>x</code> is a subset of <code>mydf</code>, with all the columns. You should not be trying to modify <code>mydf</code> from within <code>k</code>. Modify <code>x</code>, and then return the modified version. (If you must, but the options I displayed above are better.) So we might re-write your <code>k</code> like this:</p> <pre><code>k &lt;- function(x) { x$z &lt;- ifelse(x$x == 1, 0, x$n) return (x) } </code></pre> <p>Note that you've created some confusing stuff by using <code>x</code> as both an argument to <code>k</code> <em>and</em> as the name of one of our columns.</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.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      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