问题描述
我尝试在自写函数中使用 acast
来自 reshape2
,但存在问题:acast没有找到我发送给它的数据。
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 my data:
library("reshape2")
x <- data.frame(1:3, rnorm(3), rnorm(3), rnorm(3))
colnames(x) <- c("id", "var1", "var2", "var3")
y <-melt(x, id = "id", measure = c("var1", "var2", "var3"))
y
然后看起来像这样:
id variable value
1 1 var1 0.1560812
2 2 var1 1.0343844
3 3 var1 -1.4157728
4 1 var2 0.8808935
5 2 var2 0.1719239
6 3 var2 0.6723758
7 1 var3 -0.7589631
8 2 var3 1.1325995
9 3 var3 -1.5744876
现在我可以通过 acast
:
> acast(y,y[,1] ~ y[,2])
var1 var2 var3
1 0.1560812 0.8808935 -0.7589631
2 1.0343844 0.1719239 1.1325995
3 -1.4157728 0.6723758 -1.5744876
然而,当为 acast 应该这样做,我得到一个愚蠢的错误消息:
However, when writing a small wrapper for
acast
that should do the same, i get a stupid error messages:
wrap.acast <- function(dat, v1 = 1, v2 = 2) {
out <- acast(dat, dat[,v1] ~ dat[,v2])
return(out)
}
wrap.acast(y)
Error in eval(expr, envir, enclos) : object 'dat' not found
这个问题显然与环境和全局/本地变量有关。由于它在全局环境中声明
dat
后发出其他错误消息(即 v1
和 v2
,只要它们不是全局的)。
The problem is obviously related to something like environments and global/local variables. As it gives other error messages after declaring
dat
in the global environment (i.e., v1
and v2
not found as long as they aren't global).
我想使用resahpe(特别是acast)函数,而无需在函数外声明变量。什么是诀窍?
谢谢。
推荐答案
而不是使用公式规范,使用字符规范:
Instead of using the formula specification, use the character specification:
acast(y, list(names(y)[1], names(y)[2]))
这篇关于如何在R中的函数中使用acast(reshape2)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!