简体   繁体   English

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

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

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,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

So, I assume ddply is running outside of the environemtn of the function ? 因此,我假设ddply在该函数的环境之外运行? Is there a way to stop this, or am I doing something wrong ? 有什么办法可以阻止这种情况,还是我做错了什么?

Thanks 谢谢

Paul. 保罗。

You don't need get : 您不需要get

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

This is an example of this bug: http://github.com/hadley/plyr/issues#issue/3 . 这是此错误的示例: http : //github.com/hadley/plyr/issues#issue/3 But as Marek points out, you don't need get here anyway. 但是正如Marek所指出的,您还是不需要到这里来。

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

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