Reputation: 189
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
Reputation: 296
You almost had it. You just need to apply your function for each group. The purrr
library makes this pretty easy.
library(purrr)
library(dplyr)
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)
}
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))
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