简体   繁体   English

将函数中的值传递给ddply

[英]Passing a value from a function into ddply

I've got ddply constructing a data.frame along these lines: 我已经在ddply构建了一个data.frame

out <- ddply(data, .(names), varA = sum(value > 10))

That works fine, so I've tried to place it into a function 这很好,所以我试着把它放到一个函数中

func <- function(val.in) {
    out <- ddply(data, .(names), varA = sum(value > val.in))
}

func(10)

This doesn't work - it looks like ddply can't find 'val.in' 这不起作用 - 看起来ddply无法找到'val.in'

Error in eval(expr, envir, enclos) : object 'val.in' not found

Anyone know why? 谁知道为什么?

If not enough background, let me know and I'll update. 如果背景不够,请告诉我,我会更新。

I've tried to recreate your problem using some sample data from the examples under ddply . 我尝试使用ddply下的示例中的一些示例数据重新创建您的问题。

First, some sample data: 首先,一些样本数据:

dfx <- data.frame(
  group = c(rep('A', 8), rep('B', 15), rep('C', 6)),
  sex = sample(c("M", "F"), size = 29, replace = TRUE),
  age = runif(n = 29, min = 18, max = 54)
)

head(dfx)
#   group sex      age
# 1     A   F 53.08787
# 2     A   M 30.47225
# 3     A   F 26.78341
# 4     A   F 26.46841
# 5     A   F 34.65360
# 6     A   M 21.26691

Here's what you might try that would work (I assume you meant to use summarize in your question). 以下是您可能会尝试的内容(我假设您的意思是在您的问题中使用summarize )。

library(plyr)
ddply(dfx, .(group, sex), summarize, varA = sum(age > 25))
#   group sex varA
# 1     A   F    5
# 2     A   M    1
# 3     B   F    6
# 4     B   M    4
# 5     C   F    3
# 6     C   M    2

We might then try to use it in a function as follows: 然后我们可以尝试在函数中使用它,如下所示:

func <- function(val.in) {
  out <- ddply(dfx, .(group, sex), summarize, varA = sum(age > val.in))
  out
}

func(25)
# Error in eval(expr, envir, enclos) : object 'val.in' not found

^^ There's your error ^^ ^^你的错误是^^


The most straightforward solution is to use here (which helps ddply figure out where to look for things): 最直接的解决方案是在here使用(这有助于ddply找出在哪里寻找东西):

func <- function(val.in) {
  out <- ddply(dfx, .(group, sex), here(summarize), varA = sum(age > val.in))
  out
}

func(25)
#   group sex varA
# 1     A   F    5
# 2     A   M    1
# 3     B   F    6
# 4     B   M    4
# 5     C   F    3
# 6     C   M    2

Update 更新

This doesn't seem to be a problem in "dplyr" as far as I can tell: 据我所知,这在“dplyr”中似乎不是问题:

library(dplyr)
myFun <- function(val.in) {
  dfx %>% group_by(group, sex) %>% summarise(varA = sum(age > val.in))
}
myFun(10)
# Source: local data frame [6 x 3]
# Groups: group
#
#   group sex varA
# 1     A   F    5
# 2     A   M    3
# 3     B   F    7
# 4     B   M    8
# 5     C   F    2
# 6     C   M    4

Seems like you want to write an anonymous function and pass in the second argument: 好像你想编写一个匿名函数并传入第二个参数:

func<-function(val.in){
    ddply(data, .(names), function(value,val.in) data.frame(varA=sum(value>val.in)), val.in)
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM