Perform a different simple custom function based on group

I have data with three groups and would like to perform a different custom function on each of the three groups. Rather than write three separate functions, and calling them all separately, I'm wondering whether I can easily wrap all three into one function with a 'group' parameter.

For example, say I want the mean for group A:

library(tidyverse)

data(iris)

iris$Group <- c(rep("A", 50), rep("B", 50), rep("C", 50))

f_a <- function(df){
  out <- df %>% 
    group_by(Species) %>% 
    summarise(mean = mean(Sepal.Length))
  return(out)
}

The median for group B

f_b <- function(df){
  out <- df %>% 
    group_by(Species) %>% 
    summarise(median = median(Sepal.Length))
  return(out)
}

And the standard deviation for group C

f_c <- function(df){
  out <- df %>% 
    group_by(Species) %>% 
    summarise(sd= sd(Sepal.Length))
  return(out)
}

Is there any way I can combine the above functions and run them according to a group parameter?? Like: fx(df, group = "A") Which would produce the results of the above f_a function??

Keeping in mind that in my actual use context, I can't simply group_by(group) in the original function, since the actual functions are more complex. Thanks!!



from Recent Questions - Stack Overflow https://ift.tt/3taBBe0
https://ift.tt/eA8V8J

Comments

Popular posts from this blog

Today Walkin 14th-Sept

Hibernate Search - Elasticsearch with JSON manipulation

Spring Elasticsearch Operations