【问题标题】:How to find the average of several lines with the same id in a big R dataframe? [duplicate]如何在大 R 数据框中找到具有相同 id 的几行的平均值? [复制]
【发布时间】:2020-11-02 19:14:53
【问题描述】:

我有一个大数据框(超过 100 000 个条目),看起来像这样:

ID     Pre   temp  day  
134    10      6    1       
134    20      7    1        
134    10      8    1
234    5       1    2 
234    10      4    2 
234    15      10   3

我想通过查找相同 ID 值的 pre、temp 和 day 的平均值来减少我的数据框。 最后,我的数据框看起来像这样

ID   Pre   temp  day
134  13.3   7     1
234  10     5     2.3

我不知道该怎么做?

提前谢谢你!

【问题讨论】:

  • 简单,可以使用aggregate(.~ID,df,mean)
  • 只想添加data.table解决方案:dt[,.SD[,.(mean(Pre), mean(temp), mean(day))], by="ID"]

标签: r dataframe mean


【解决方案1】:

使用dplyr 包,您可以group_by 您的ID 值,然后使用summarise 取平均值

library(dplyr)
df %>% 
  group_by(ID) %>% 
  summarise(Pre= mean(Pre),
            temp = mean(temp),
            day = mean(day))
# A tibble: 2 x 4
     ID   Pre  temp   day
  <dbl> <dbl> <dbl> <dbl>
1   134  13.3     7  1   
2   234  10       5  2.33

【讨论】:

    【解决方案2】:

    使用 dplyr,解决方案如下所示:

    textFile <- "ID     Pre   temp  day  
    134    10      6    1       
    134    20      7    1        
    134    10      8    1
    234    5       1    2 
    234    10      4    2 
    234    15      10   3"
    
    data <- read.table(text = textFile,header=TRUE)
    
    library(dplyr)
    
    data %>% group_by(ID) %>%
         summarise(.,Pre = mean(Pre),temp = mean(temp),day=mean(day))
    

    ...和输出:

      <int> <dbl> <dbl> <dbl>
    1   134  13.3     7  1   
    2   234  10       5  2.33
    >  
    

    【讨论】:

      【解决方案3】:

      你可以试试下一个:

      library(dplyr)
      
      #Data
      df <- structure(list(ID = c(134L, 134L, 134L, 234L, 234L, 234L), Pre = c(10L, 
      20L, 10L, 5L, 10L, 15L), temp = c(6L, 7L, 8L, 1L, 4L, 10L), day = c(1L, 
      1L, 1L, 2L, 2L, 3L)), class = "data.frame", row.names = c(NA, 
      -6L))
      
      #Code
      df %>% group_by(ID) %>% summarise_all(mean,na.rm=T)
      
      # A tibble: 2 x 4
           ID   Pre  temp   day
        <int> <dbl> <dbl> <dbl>
      1   134  13.3     7  1   
      2   234  10       5  2.33
      

      不需要设置每个单独的变量。

      【讨论】:

        猜你喜欢
        • 2021-10-12
        • 2020-07-13
        • 1970-01-01
        • 1970-01-01
        • 2018-04-05
        • 2015-05-06
        • 1970-01-01
        • 1970-01-01
        • 2020-12-26
        相关资源
        最近更新 更多