ddply 在函数中运行会查看函数外部的环境吗?
我正在尝试编写一个函数来进行一些经常重复的分析,其中一部分是计算组数和每个组内的成员数,因此 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 正在运行在函数的环境之外?有没有办法阻止这种情况,或者我做错了什么?
谢谢
保罗。
I'm trying to write a function to do some often repeated analysis, and one part of this is to count the number of groups and number of members within each group, so ddply to the rescue !, however, my code has a problem....
Here is some example data
> 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")
and here is my code
foo<-function(exp1, exp2, data) {
datadesc<-ddply(data, .(with(data, get(exp2))), nrow)
return(datadesc)
}
If I run this function, I get an error
> foo(exp="Machine",exp1="weight",data=BGBottles)
Error in eval(substitute(expr), data, enclos = parent.frame()) :
invalid 'envir' argument
However, if I define my exp1, exp2 and data variables int he global environemtn first, it works
> 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
So, I assume ddply is running outside of the environemtn of the function ? Is there a way to stop this, or am I doing something wrong ?
Thanks
Paul.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您不需要
get
:You don't need
get
:这是此错误的示例: http://github.com/hadley/plyr/问题#issue/3。但正如马雷克指出的那样,你无论如何都不需要到这里来。
This is an example of this bug: http://github.com/hadley/plyr/issues#issue/3. But as Marek points out, you don't need get here anyway.