How to use acast (reshape2) within a function in R?

后端 未结 4 1610
感动是毒
感动是毒 2021-02-09 10:40

I tried to use acast from reshape2 within a self written function, but had the problem that acast did not find the data I send to it.

Here is m

4条回答
  •  天涯浪人
    2021-02-09 11:08

    One issue is that you are abusing the formula notation in R. You shouldn't do things like

    > acast(y, y[,1] ~ y[,2])
            var1       var2         var3
    1  2.1726117  0.6107264  0.291446236
    2  0.4755095 -0.9340976 -0.443291873
    3 -0.7099464 -1.2536334  0.001105352
    

    as the 'y' bits are redundant if a data object is supplied. If you refer to the variables of y by name directly in the formula, things work nicely

    > acast(y, id ~ variable)
            var1       var2         var3
    1  2.1726117  0.6107264  0.291446236
    2  0.4755095 -0.9340976 -0.443291873
    3 -0.7099464 -1.2536334  0.001105352
    

    and the code is much more readable in this second version.

    To do what you want using the acast wrapper is going to involve generating the correct formula using the names, as Joris points out, and Hadley's solution is much simpler. So my point really is to watch out with how you use formula specification in R. You'll save yourself a lot of trouble in the long run (though not specifically with this particular problem) if you use formulas properly.

提交回复
热议问题