ddply在函数中运行在函数外部的环境中? [英] ddply run in a function looks in the environment outside the function?

查看:85
本文介绍了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....

以下是一些示例数据

> 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)
}

如果我运行此功能,则会出现错误

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

但是,如果我先在全局环境中定义exp1,exp2和数据变量,则它可以正常工作

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

因此,我假设ddply在函数的environemtn之外运行?有什么办法可以阻止这种情况,还是我做错了什么?

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 ?

谢谢

保罗.

推荐答案

这是此错误的示例:

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.

这篇关于ddply在函数中运行在函数外部的环境中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆