2010-06-30 66 views
2

我想寫一個函數做一些經常重複的分析,其中一部分是計算每個組內的成員數量和成員數量,所以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和數據變量第一詮釋,他的全球environemtn,它的工作原理

> 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 

所以,我認爲該功能的environemtn的ddply運行之外?有沒有辦法阻止這個,或者我做錯了什麼?

感謝

保羅。

回答

3

你不需要get

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