【问题标题】:How to calculate difference between first and last score如何计算第一个和最后一个分数之间的差异
【发布时间】:2023-01-30 22:53:57
【问题描述】:

我想根据日期计算每个人的第一个和最后一个分数之间的差异。原始数据如下所示:

ID <- c(1,1,1,2,2,3,3,3,3,4)
Score <- c(3,2,1,1,2,0,0,3,4,0)
Date <- c("2020/01/01","2020/01/02","2020/01/03","2020/02/05","2020/02/06","2021/10/01","2021/10/02","2021/10/03","2021/10/04","2022/03/01")

a <- data.frame(ID,Score,Date)

所需的数据集:

diff_first_last <- c(-2,-2,-2,1,1,4,4,4,4,0)
b <- data.frame(ID,Score,Date,diff_first_last)

有没有办法轻松做到这一点,因为我想将它应用于更大的数据集。 我将不胜感激所有的帮助!谢谢!!!

【问题讨论】:

    标签: r


    【解决方案1】:

    这是一种可能的 dplyr 解决方案:

    library(dplyr)
    # build groupings by ID
    dplyr::group_by(a, ID) %>%
        # convert date from text to date to be able to order by it
        dplyr::mutate(Date = lubridate::ymd(Date)) %>% 
        # order by date just to be sure
        dplyr::arrange(Date) %>%
        # calculate first last diference 
        mutate(diff_first_last = dplyr::last(Score) - dplyr::first(Score)) %>%
        # ungroup to prevent unwanted behaviour downstream
        dplyr::ungroup()
    
     # A tibble: 10 x 4
          ID Score Date       diff_first_last
       <dbl> <dbl> <date>               <dbl>
     1     1     3 2020-01-01              -2
     2     1     2 2020-01-02              -2
     3     1     1 2020-01-03              -2
     4     2     1 2020-02-05               1
     5     2     2 2020-02-06               1
     6     3     0 2021-10-01               4
     7     3     0 2021-10-02               4
     8     3     3 2021-10-03               4
     9     3     4 2021-10-04               4
    10     4     0 2022-03-01               0
    

    【讨论】:

      【解决方案2】:

      您可以使用 ave 假设它是按日期排序的。

      ave(a$Score, a$ID, FUN = (x) x[length(x)] - x[1])
      # [1] -2 -2 -2  1  1  4  4  4  4  0
      

      万一它没有排序。

      a <- a[order(as.Date(a$Date)),]
      

      【讨论】:

        猜你喜欢
        • 2020-05-25
        • 1970-01-01
        • 2023-03-21
        • 2022-11-30
        • 2021-11-19
        • 1970-01-01
        • 1970-01-01
        • 2018-10-14
        • 2020-05-28
        相关资源
        最近更新 更多