Pass a ddply function wrapped inside a function as part of a call to these functions

I hope to use ddply inside the function to summarize groups based on user-defined statistics (e.g. average, median, minimum, maximum), passing the name of the summary function to use as a variable in the call function. However, I'm not sure how to pass this to ddply.

Simple for example

library(plyr)
test.df<-data.frame(group=c("a","a","b","b"),value=c(1,5,5,15))
ddply(test.df,.(group),summarise, mean=mean(value, na.rm=TRUE))

how can I set it somehow like below, with the corresponding function passed to ddply (optionally within the function, of course, although this should be simple as soon as the first problem is solved). Note that each summary measure (average, etc.) will require na.rm = TRUE. I could do this by writing my own replacement function for each summary statistic, but that seems too complicated.

Desired:

#fn<-"mean"     
#ddply(test.df,.(group),summarise, fn=fn(value, na.rm=TRUE))

Thanks for any help people can provide.

! . , , getFunction match.fun , fn . , , - - ( ). , ...

test.df<-data.frame(group=c("a","a","b","b"),value=c(1,5,5,15))
my.fun <- function(df, fn="mean") {
    summary <- ddply(df,.(group),summarise, summary=match.fun(fn)(value, na.rm=T))
  return(summary)
}
my.fun(test.df, fn="mean")
+4
3

, , , . ( , , , ). , (Iwastemptedtoanswerequestionwithoutanyspacesinither);

df <- data.frame(
  group = c("a", "a" ,"b" ,"b" ), 
  value = c(1, 5, 5, 15)
)

my_fun <- function(df, fn = "mean") {
  fn <- match.fun(fn)
  ddply(df, .(group), summarise, summary = fn(value, na.rm = TRUE))
}

, , , , ( ). summarise() , . value, fn, , summarise() , .. ddply().

:

  • here(), ​​ plyr

    my_fun <- function(df, fn = "mean") {
      fn <- match.fun(fn)
      ddply(df, .(group), here(summarise), summary = fn(value, na.rm = TRUE))
    }
    my_fun(df, "mean")
    
  • :

    my_fun <- function(df, fn = "mean") {
      fn <- match.fun(fn)
      ddply(df, .(group), function(df) {
        summarise(df, summary = fn(value, na.rm = TRUE))
      })
    }
    my_fun(df, "mean")
    

, plyr, C/++. dplyr, plyr, .

+4

getFunction:

fn<-"mean"     
ddply(test.df,.(group),summarise, fn=getFunction(fn)(value, na.rm=TRUE))
#  group fn
#1     a  3
#2     b 10

, , .

+2

It works with match.fun:

fn <- "mean"

ddply(test.df, .(group), summarise, fn = match.fun(fn) (value, na.rm = TRUE))
#  group fn
# 1     a  3
# 2     b 10
+1
source

All Articles