将函数参数传递给ddply

时间:2015-05-26 15:52:48

标签: r function plyr

我知道有各种类似的问题,因此我对重复进行了粗暴的讨论。也就是说,虽然我已经找到了关于这个主题的有用信息,但我所尝试的一切似乎都没有用。

简而言之,我在函数内部使用ddply,并尝试将函数中的参数传递给ddply中的函数。

使用iris数据集

的简化示例
IG_test <-function(data, feature){
  dd<-ddply(data, feature, here(summarise), N=length(feature))
  return(dd)
}

IG_test(iris, "Species")

这应该返回每个物种的记录数,而是在每种情况下返回1。

如果我直接在length()中指定“物种”,我会得到我正在寻找的物品

IG_test <-function(data, feature){
  dd<-ddply(data, feature, here(summarise), N=length(Species))
  return(dd)
}

    IG_test(iris, "Species")

     Species  N
1     setosa 50
2 versicolor 50
3  virginica 50

描述类似问题的最新问题建议在ddply中使用here()作为summarize()函数,以便告诉ddply在哪里查找变量。这样做是因为feature被找到(没有here()我们得到一个错误),但它没有按预期返回长度。

有什么想法吗?

1 个答案:

答案 0 :(得分:2)

您将字符串名称“Species”传递给ddply函数。所以你应该在里面得到它的价值。然后ddply识别列名

library(plyr)
IG_test <-function(data, feature){
  dd<-ddply(data, feature, here(summarise), N=length(get(feature)))
  return(dd)
}

IG_test(iris, "Species")