折叠具有重复 ID 和所有其他变量的平均值的行

Collapse rows with duplicate ID and average values of all other variables

我使用的数据集有几千个单词,每个单词有超过 60 个值。大多数单词都是独一无二的,但也有一些是重复的。我想合并这些并用平均值替换相关值。如果有一种方法可以做到这一点而不必指定重复的单词,那就太好了。

所以从这里开始:

Word    measure1    measure2    measure3 
aids    3.52        2.2         21 
aids    1.33        0.8         21  
coke    6.55        1.99        22  
coke    6.62        1.91        21  

为此:

Word    measure1    measure2    measure3 
aids    2.425       1.5         21  
coke    6.585       1.95        21.5 

(我正在使用 this 数据)

你可以使用

library(dplyr)

df1 %>% 
  group_by(Word) %>% 
  summarise(across(where(is.numeric), mean))

这个returns

# A tibble: 2 x 4
  Word  measure1 measure2 measure3
  <chr>    <dbl>    <dbl>    <dbl>
1 aids     2.425     1.5      21  
2 coke     6.585     1.95     21.5