繁体   English   中英

ddply在函数中运行在函数外部的环境中?

[英]ddply run in a function looks in the environment outside the function?

我正在尝试编写一个函数来进行一些经常重复的分析,而其中的一部分是计算组的数量和每个组中的成员数量,因此请尝试一下!但是,我的代码有问题。 ...

这是一些示例数据

> 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在该函数的环境之外运行? 有什么办法可以阻止这种情况,还是我做错了什么?

谢谢

保罗。

您不需要get

foo<-function(exp1, exp2, data) {
    datadesc<-ddply(data, exp2, nrow)
    return(datadesc)
}

这是此错误的示例: http : //github.com/hadley/plyr/issues#issue/3 但是正如Marek所指出的,您还是不需要到这里来。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM