简体   繁体   English

如何通过外部函数调用将分组变量传递给ddply?

[英]How to pass grouping variables to ddply from outside function call?

I have a bunch of functions that are wrappers for ddply and other plyr functions. 我有一堆函数,它们是ddply和其他plyr函数的包装器。 I occasionally need to change the grouping variables that I use in those functions and I'd like to keep them in a global variable so I only have to change one thing to effect the behavior of all the functions. 有时我需要更改在这些函数中使用的分组变量,并且希望将它们保留在全局变量中,因此我只需要更改一件事即可影响所有函数的行为。 Here's what I'm trying. 这就是我正在尝试的。

# Grouping variables to pass to ddply
params = c('density', 'decay_rate', 'scale', 'exponent', 'max_distance')
location = c('grid_x', 'grid_y', 'dataset_x', 'dataset_y')


mean_d <- function(df) {

  # mean function to call from ddply
  mean_likelihood <- function (x) {
    mean_likelihood <- mean(x$likelihood)
    return(mean_likelihood)
  }

# This doesn't work.
# mean_df <- ddply(df, .(seed, params, location), mean_likelihood)

# This works
  mean_df <- ddply(df, .(seed,
                         density, decay_rate, scale, exponent,
                         max_distance, grid_x, grid_y, dataset_x, dataset_y),
                         mean_likelihood)

  names(mean_df)[length(names(mean_df))] <- 'mean_likelihood'

  return(mean_df)
}
library(ggplot2)
data(diamonds)
small_diamonds <- diamonds[sample(nrow(diamonds), 100), ]
set1 <- c("cut", "color")
set2 <- c("cut", "color", "clarity")

foo <- function(df) {
    return(df[which.max(df$depth), ])
}

ddply(small_diamonds, set1, foo)
ddply(small_diamonds, set2, foo)

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

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