【问题标题】:Collapse rows with duplicate ID and average values of all other variables折叠具有重复 ID 的行和所有其他变量的平均值
【发布时间】:2021-12-23 07:59:51
【问题描述】:

我正在使用一个包含数千个单词的数据集,以及与每个单词相关的 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数据)

【问题讨论】:

标签: r duplicates


【解决方案1】:

你可以使用

library(dplyr)

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

返回

# 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

【讨论】:

    猜你喜欢
    • 2011-02-03
    • 1970-01-01
    • 2022-11-10
    • 1970-01-01
    • 2020-05-19
    • 2021-06-14
    • 1970-01-01
    • 1970-01-01
    • 2017-06-04
    相关资源
    最近更新 更多