Note that there are some explanatory texts on larger screens.

plurals
  1. POR ddply, applying if and ifelse functions
    primarykey
    data
    text
    <p>I'm trying to apply a function to a dataframe using ddply from the plyr package, but I'm getting some results that I don't understand. I have 3 questions about the results </p> <p>Given:</p> <pre><code>mydf&lt;- data.frame(c(12,34,9,3,22,55),c(1,2,1,1,2,2) , c(0,1,2,1,1,2)) colnames(mydf)[1] &lt;- 'n' colnames(mydf)[2] &lt;- 'x' colnames(mydf)[3] &lt;- 'x1' </code></pre> <p>mydf looks like this:</p> <pre><code> n x x1 1 12 1 0 2 34 2 1 3 9 1 2 4 3 1 1 5 22 2 1 6 55 2 2 </code></pre> <h3>Question #1</h3> <p>If I do:</p> <pre><code>k &lt;- function(x) { mydf$z &lt;- ifelse(x == 1, 0, mydf$n) return (mydf) } mydf &lt;- ddply(mydf, c("x") , .fun = k, .inform = TRUE) </code></pre> <p>I get the following error:</p> <pre><code>Error in `$&lt;-.data.frame`(`*tmp*`, "z", value = structure(c(12, 34, 9, : replacement has 3 rows, data has 6 Error: with piece 1: n x x1 1 12 1 0 2 9 1 2 3 3 1 1 </code></pre> <p>I get this error regardless of whether I specify the variable to split by as c("x"), "x", or .(x). I don't understand why I'm getting this error message.</p> <h3>Question #2</h3> <p>But, what I really want to do is set up an if/else function because my dataset has variables x1, x2, x3, and x4 and I want to take those variables into account as well. But when I try something simple such as:</p> <pre><code>j &lt;- function(x) { if(x == 1){ mydf$z &lt;- 0 } else { mydf$z &lt;- mydf$n } return(mydf) } mydf &lt;- ddply(mydf, x, .fun = j, .inform = TRUE) </code></pre> <p>I get:</p> <pre><code>Warning messages: 1: In if (x == 1) { : the condition has length &gt; 1 and only the first element will be used 2: In if (x == 1) { : the condition has length &gt; 1 and only the first element will be used </code></pre> <h3>Question #3</h3> <p>I'm confused about to use function() and when to use function(x). Using function() for either j() or k() gives me a different error:</p> <pre><code>Error in .fun(piece, ...) : unused argument (piece) Error: with piece 1: n x x1 z 1 12 1 0 12 2 9 1 2 9 3 3 1 1 3 4 12 1 0 12 5 9 1 2 9 6 3 1 1 3 7 12 1 0 12 8 9 1 2 9 9 3 1 1 3 10 12 1 0 12 11 9 1 2 9 12 3 1 1 3 </code></pre> <p>where column z is not correct. Yet I see a lot of functions written as function().</p> <p>I sincerely appreciate any comments that can help me out with this</p>
    singulars
    1. This table or related slice is empty.
    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