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

后端 未结 4 1506
感动是毒
感动是毒 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:10

    Correction : problem is not that it doesn't find dat, but that it doesn't find dat[,v1] and dat[,v2] in the specified formula. Acast takes an argument of the type formula, and that one gets evaluated in a temporary environment created around your data frame. Within that environment, it doesn't find a "dat" object when the function is wrapped within another.

    I'm not completely following as to how this does work in the global and doesn't when wrapped, but if you feed acast a formula, it does work within a function as well.

    wrap.acast <- function(dat, v1 = 1, v2 = 2) {
        x1 <- names(dat)[v1]
        x2 <- names(dat)[v2]
        form <- as.formula(paste(x1,"~",x2))
        out <- acast(dat,form)
        return(out)
    }
    

    using your toy data :

    > wrap.acast(y)
            var1      var2       var3
    1 0.04095337 0.4044572 -0.4532233
    2 1.23905358 1.2493187  0.7083557
    3 0.72798307 0.7868746  1.7144811
    

提交回复
热议问题