【问题标题】:How to get the difference between groups with a dataframe in long format in R?如何在 R 中获取具有长格式数据框的组之间的差异?
【发布时间】:2021-01-09 04:16:56
【问题描述】:

有一个包含 2 个 ID (N = 2) 和 2 个句点 (T = 2) 的简单数据框,例如:

 year    id    points
   1      1     10
   1      2     12
   2      1     20
   2      2     18

如何实现以下数据帧(最好使用 dplyr 或任何 tidyverse 解决方案)?

 id    points_difference
  1         10   
  2         6   

请注意,points_difference 列是每个 ID 在跨时间(即 T2 - T1)之间的差异。

另外,如何对多列多ID(只有2个句点)进行泛化?

 year    id    points  scores
   1      1      10      7
   1     ...    ...     ...
   1      N      12      8
   2      1      20      9
   2     ...    ...     ...
   2      N      12      9

 id    points_difference   scores_difference
  1         10                     2
 ...        ...                   ...
  N          0                     1  

【问题讨论】:

    标签: r dataframe dplyr tidyverse panel-data


    【解决方案1】:

    如果您使用的是dplyr 1.0.0(或更高版本),summarise 可以在输出中返回多行,因此如果您有两个以上的句点,这也将起作用。你可以这样做:

    library(dplyr)
    
    df %>%
      arrange(id, year) %>%
      group_by(id) %>%
      summarise(across(c(points, scores), diff, .names = '{col}_difference'))
    
    #     id points_difference scores_difference
    #  <int>             <int>             <int>
    #1     1                10                 2
    #2     1                -7                 1
    #3     2                 6                 2
    #4     2                -3                 3
    

    数据

    df <- structure(list(year = c(1L, 1L, 2L, 2L, 3L, 3L), id = c(1L, 2L, 
    1L, 2L, 1L, 2L), points = c(10L, 12L, 20L, 18L, 13L, 15L), scores = c(2L, 
    3L, 4L, 5L, 5L, 8L)), class = "data.frame", row.names = c(NA, -6L))
    

    【讨论】:

    • 我们可以arrangegroup by两个ID变量吗?
    • group_by(id1, id2)有什么不同吗?
    猜你喜欢
    • 2018-09-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-14
    • 1970-01-01
    相关资源
    最近更新 更多