R:函数内部的dcast找不到传递的变量

时间:2018-09-21 02:38:02

标签: r function variables get dcast

我有以下data.frame

> mydata <- data.frame(gene=rep(paste(sample(LETTERS, 10, replace=TRUE), sample(1:1000, 10, replace=FALSE), sep=''), each=5),
+                    clus=rep(sample(c('clus1','clus2'),10,replace=TRUE), each=5),
+                    treat=rep(LETTERS[1:5],10),
+                    value=rnorm(n=50))
> head(mydata,10)
   gene  clus treat       value
1   R22 clus2     A -0.25592597
2   R22 clus2     B  0.02956595
3   R22 clus2     C  0.36785764
4   R22 clus2     D -1.47393076
5   R22 clus2     E -2.09895513
6  S671 clus2     A -0.17079390
7  S671 clus2     B  1.73643010
8  S671 clus2     C  0.73169650
9  S671 clus2     D -0.85247328
10 S671 clus2     E  1.43589407

我有一个通用功能,其中第一步是像这样dcastdata.frame

> dcast(mydata, gene+clus~treat, value.var="value")
   gene  clus          A           B            C          D           E
1  B957 clus1 -2.0567334  2.27900277  0.714784782  2.5123012 -0.91194409
2   I55 clus2 -1.3044907 -1.06102427 -0.380294765 -0.1194413  1.90913241
3  M937 clus1 -2.1610684  1.82269937  0.716722593 -0.1525909  0.92291856
4  N986 clus1  0.2483086 -0.41405923 -0.714040214 -0.4243231  0.13645697
5   R22 clus2 -0.2559260  0.02956595  0.367857644 -1.4739308 -2.09895513
6  R295 clus2 -0.4673256  0.08302997 -0.352803402  0.2983689  1.25420084
7  R545 clus1  2.5655384 -0.14798670  1.001409732  0.1971712 -0.11440350
8  S671 clus2 -0.1707939  1.73643010  0.731696498 -0.8524733  1.43589407
9  W131 clus1  0.9915700  0.05430845  0.008878675 -1.7140515  0.06019417
10 Z302 clus1  1.2854086  0.09809435 -2.533077634 -1.0244764 -0.57606345

虽然这在函数外部起作用,但似乎在内部不起作用...我有这个最小的函数:

myfun <- function(mydf, groupvar, groupvar2, measurevar, valuevar){
    newdf <- dcast(mydf, get(measurevar)+get(groupvar2)~get(groupvar), value.var=valuevar)#cannot change sep from "_"
}

但是当我调用它时,出现以下错误:

> myfun(mydata, "treat", "clus", "gene", "value")
  

get(measurevar)中的错误:找不到对象“ measurevar”

为什么我的函数找不到我传递的变量measurevar

但是,如果我在return之前dcast,它会毫无问题地返回它,并且dcast突然起作用:

> myfun <- function(mydf, groupvar, groupvar2, measurevar, valuevar){
+     return(list(groupvar,groupvar2,measurevar,valuevar))
+     newdf <- dcast(mydf, get(measurevar)+get(groupvar2)~get(groupvar), value.var=valuevar)#cannot change sep from "_"
+ }
> myfun(mydata, "treat", "clus", "gene", "value")
[[1]]
[1] "treat"

[[2]]
[1] "clus"

[[3]]
[1] "gene"

[[4]]
[1] "value"

这是怎么回事?我真的什么都不懂……为什么dcast找不到我传递的变量measurevar,但是如果我先返回它,突然之间就会知道吗?

谢谢!

0 个答案:

没有答案