我正在尝试编写一个函数来进行一些经常重复的分析,其中一部分是计算组数和每个组内的成员数,所以 ddply 救援!但是,我的代码有问题。 ...
这是一些示例数据
> dput(BGBottles)
structure(list(Machine = structure(c(1L, 1L, 1L, 2L, 2L, 2L,
3L, 3L, 3L, 4L, 4L, 4L), .Label = c("1", "2", "3", "4"), class = "factor"),
weight = c(14.23, 14.96, 14.85, 16.46, 16.74, 15.94, 14.98,
14.88, 14.87, 15.94, 16.07, 14.91)), .Names = c("Machine",
"weight"), row.names = c(NA, -12L), class = "data.frame")
这是我的代码
foo<-function(exp1, exp2, data) {
datadesc<-ddply(data, .(with(data, get(exp2))), nrow)
return(datadesc)
}
如果我运行这个函数,我会得到一个错误
> foo(exp="Machine",exp1="weight",data=BGBottles)
Error in eval(substitute(expr), data, enclos = parent.frame()) :
invalid 'envir' argument
但是,如果我首先在全局环境中定义我的 exp1、exp2 和数据变量,它就可以工作
> exp1<-"weight"
> exp2<-"Machine"
> data<-BGBottles
> foo(exp="Machine",exp1="weight",data=BGBottles)
with.data..get.exp2.. V1
1 1 3
2 2 3
3 3 3
4 4 3
所以,我假设 ddply 在函数的 environemtn 之外运行?有没有办法阻止这种情况,或者我做错了什么?
谢谢
保罗。