在函数中使用ddply [英] Using ddply inside a function

查看:89
本文介绍了在函数中使用ddply的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在其中使用ddply创建一个函数.但是我不能上班.这是一个重现我所得到的虚拟例子.这有什么事此错误吗?

I'm trying to make a function using ddply inside of it. However I can't get to work. This is a dummy example reproducing what I get. Does this have anything to do this bug?

library(ggplot2)
data(diamonds)

foo <- function(data, fac1, fac2, bar) {
  res <- ddply(data, .(fac1, fac2), mean(bar))
  res
}

foo(diamonds, "color", "cut", "price")

推荐答案

我不认为这是一个错误. ddply需要一个函数的名称,而mean(bar)并未真正提供该函数的名称.您需要编写一个完整的函数来计算您想要的均值:

I don't believe this is a bug. ddply expects the name of a function, which you haven't really supplied with mean(bar). You need to write a complete function that calculates the mean you'd like:

foo <- function(data, fac1, fac2, bar) {
  res <- ddply(data, c(fac1, fac2), function(x,ind){
                                     mean(x[,ind]},bar)
  res
}

此外,您不应该将字符串传递给.(),因此我将其更改为c(),以便可以将函数参数直接传递给ddply.

Also, you shouldn't pass strings to .(), so I changed that to c(), so that you can pass the function arguments directly to ddply.

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

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