计算不同列数的分组平均值

时间:2021-05-06 06:16:40

标签: r dplyr

我有一个(非常大的)数据框,其中包含 w 不同 size 和语料库 f 话语中的命令:

df <- structure(list(size = c(2, 2, 3, 3, 4, 4, 3, 3), 
                     w1 = c("come", "why", "er", "well", "i", "no", "that", "cos"), 
                     w2 = c("on","that", "i", "not", "'m", "thanks", "'s", "she"), 
                     w3 = c(NA, NA, "can", "today", "going", "a", "cool", "does"), 
                     w4 = c(NA,NA, NA, NA, "home", "lot", NA, NA), 
                     f1 = c(9699L, 6519L, 21345L, 35793L, 169024L, 39491L, 84682L, 11375L), 
                     f2 = c(33821L, 84682L,169024L, 21362L, 14016L, 738L, 107729L, 33737L), 
                     f3 = c(NA, NA,  15428L, 2419L, 10385L, 77328L, 132L, 7801L), 
                     f4 = c(NA, NA, NA, NA, 2714L, 3996L, NA, NA)), 
                row.names = c(NA, -8L), class = "data.frame")

我需要计算不同列数的不同 size 组的平均值。我可以通过size做到size,就像这样,例如对于size == 2

# calculate numbers of rows per size group:
RowsPerSize <- table(df$size) 

# make size subset:                   
df_size2 <- df[df$size == 2,] 

# calculate average `f`requencies per `size`:                    
AvFreqSize_2 <- apply(df_size2[,6:7], 2, function(x) sum(x, na.rm = T)/RowsPerSize[1])

# result:
AvFreqSize_2
     f1      f2 
 8109.0 59251.5

但这对于单个 size 来说已经很麻烦了,对于多个 size 来说更是如此。我很确定有一种更经济的方式,可能在 dplyr,您可以group_by。一个不起眼的开始是这样的:

df %>%
  group_by(size) %>%
  summarise(freq = n())
# A tibble: 3 x 2
   size  freq
* <dbl> <int>
1     2     2
2     3     4
3     4     2

1 个答案:

答案 0 :(得分:1)

我猜了很多,但我认为您正在寻找这个:

library(tidyverse)

df %>%
  group_by(size) %>%
  summarise(across(matches("f\\d"), ~sum(.x, na.rm = T)/n()))
#> # A tibble: 3 x 5
#>    size      f1     f2     f3    f4
#>   <dbl>   <dbl>  <dbl>  <dbl> <dbl>
#> 1     2   8109  59252.     0      0
#> 2     3  38299. 82963   6445      0
#> 3     4 104258.  7377  43856.  3355


#as @Onyambu suggested, it could make more sense to use `mean()`
df %>%
  group_by(size) %>%
  summarise(across(matches("f\\d"), ~mean(.x, na.rm = T)))
#> # A tibble: 3 x 5
#>    size      f1     f2     f3    f4
#>   <dbl>   <dbl>  <dbl>  <dbl> <dbl>
#> 1     2   8109  59252.   NaN    NaN
#> 2     3  38299. 82963   6445    NaN
#> 3     4 104258.  7377  43856.  3355

reprex package (v2.0.0) 于 2021 年 5 月 6 日创建