簡體   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