首页 > 解决方案 > 计算不同列数的分组平均值

问题描述

我有一个(非常大的)数据框,其中w包含不同sizes 的话语和单词的语料库frequencies 中的 ords:

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列数的不同组的平均值。我可以这样做sizesize就像这样,例如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

但这对于单个 s 来说已经很麻烦了,对于多个ssize来说更是如此。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

标签: rdplyr

解决方案


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

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 包于 2021-05-06 创建 (v2.0.0 )


推荐阅读