Coolsun
Coolsun

Reputation: 189

Apply custom function to multiple groups in R

I am trying to apply a custom function across all groups of my dataset.

I tried applying the below custom function across all groups but its being applied on overall data set. But if I break my data into multiple groups & apply each group to this function its working well.

Upvotes: 1

Views: 635

Answers (1)

Seth Raithel
Seth Raithel

Reputation: 296

You almost had it. You just need to apply your function for each group. The purrr library makes this pretty easy.

Libraries:

library(purrr)
library(dplyr)

Main function:

Takes group name and full data set as arguments, then filters by that group. Then makes calculations and returns them as a dataframe.

width <- function(Group.Name, data){
  # limit to rows for that group
  df<-data %>% filter(Group == Group.Name)
  
  i.mins  <- which(diff(sign(diff(c(Inf, df$Value, Inf)))) == 2)
  
  i.mx <- which.max(df$Value)
  
  i <- sort(c(i.mins, i.mx))
  
  ix <- i[which(i == i.mx) + c(-1, 1)]
  
  # put results in dataframe
  df <- data.frame("Group" = Group.Name, "Value_1" = ix[1], "Value_2" = ix[2])
  
  # format Group Col
  df$Group <- as.character(df$Group)
  return(df)
}

Looping through groups with purrr

# unique group names we need to loop through for calcs
Group.Names <- unique(data$Group)

# take each name and use the width function
# then put results together in one datframe
Group.Names %>% map_df(~ width(Group.Name = .x, data = data))

Results:

   Group Value_1 Value_2
1 Group1      16      22
2 Group2       4      12
3 Group3       2      15

Note: the .x notation just tells map to put the Group.Names object as the first argument in our width function

Upvotes: 2

Related Questions