将函数参数传递给ddply

3

我知道有很多类似的问题,因此对于重复我表示歉意。尽管如此,在这个主题上我找到了有用的信息,但我尝试的所有内容似乎都不起作用。

简而言之,我正在函数内部使用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的summarize()函数中使用here(),以告诉ddply在哪里查找变量。这样可以解决feature未被找到的错误,但是它并没有像预期的那样返回长度。
有什么想法吗?
1个回答

3
你正在向ddply函数传递一个名为“Species”的字符串。因此,你需要在内部获取它的值。然后ddply会识别列名。
library(plyr)
IG_test <-function(data, feature){
  dd<-ddply(data, feature, here(summarise), N=length(get(feature)))
  return(dd)
}

IG_test(iris, "Species")

太棒了!这正是我在寻找的,谢谢。也感谢您的解释。 - philjet

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接