【问题标题】:Adding the data of different rows which share the same date in R在R中添加共享相同日期的不同行的数据
【发布时间】:2020-05-02 15:45:22
【问题描述】:

我在 R 中有以下数据框:

      Date        A   B    C

1  2015-01-17     1   NA   1
2  2015-01-18     NA  NA   NA
3  2015-01-19     1   2    3
4  2015-01-19     1   NA   1
...

目标是具有相同日期的不同行在 A、B、C 列中添加它们的值:

      Date        A   B    C

1  2015-01-17     1   NA   1
2  2015-01-18     NA  NA   NA
3  2015-01-19     2   2    4
...

感谢您的帮助。

【问题讨论】:

    标签: r time-series


    【解决方案1】:
    library(dplyr)
    df %>%
      group_by(Date)%>%
      summarise_at(.,c("A","B","C"),function(x) if(any(!is.na(x)))sum(x,na.rm = T) else NA)
    
    
    # A tibble: 3 x 4
      Date           A     B     C
      <fct>      <int> <int> <int>
    1 2015-01-17     1    NA     1
    2 2015-01-18    NA    NA    NA
    3 2015-01-19     2     2     4
    

    数据:

    df <- structure(list(Date = structure(c(1L, 2L, 3L, 3L), .Label = c("2015-01-17", 
    "2015-01-18", "2015-01-19"), class = "factor"), A = c(1L, NA, 
    1L, 1L), B = c(NA, NA, 2L, NA), C = c(1L, NA, 3L, 1L)), class = "data.frame", row.names = c("1", 
    "2", "3", "4"))
    

    【讨论】:

      【解决方案2】:

      另一个选项是sum_ 来自hablar

      library(hablar)
      library(dplyr)
      df %>% 
          group_by(Date) %>%
          summarise_if(is.numeric, sum_)
      # A tibble: 3 x 4
      #  Date           A     B     C
      #  <fct>      <int> <int> <int>
      #1 2015-01-17     1    NA     1
      #2 2015-01-18    NA    NA    NA
      #3 2015-01-19     2     2     4
      

      数据

      df <- structure(list(Date = structure(c(1L, 2L, 3L, 3L), .Label = c("2015-01-17", 
      "2015-01-18", "2015-01-19"), class = "factor"), A = c(1L, NA, 
      1L, 1L), B = c(NA, NA, 2L, NA), C = c(1L, NA, 3L, 1L)), 
      class = "data.frame", row.names = c("1", 
      "2", "3", "4"))
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2018-07-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-03-07
        • 1970-01-01
        相关资源
        最近更新 更多