简体   繁体   English

将自定义功能应用于R中的多个组

[英]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. 但是,如果我将数据分为多个组并将每个组应用于此功能,则效果很好。

You almost had it. 你差点就吃了。 You just need to apply your function for each group. 您只需要为每个组应用功能。 The purrr library makes this pretty easy. purrr库使此操作非常容易。

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 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 注意: .x表示法只是告诉map将Group.Names对象作为宽度函数中的第一个参数

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

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