【问题标题】:Is there an R function that calculates the amount of days since the most recent date in a data frame?是否有一个 R 函数可以计算自数据框中最近日期以来的天数?
【发布时间】:2022-01-19 14:41:30
【问题描述】:

我有下面的数据框,想计算自当前日期以来学生最后一次(最近一次)缺勤的天数,并将其添加到原始数据框中。

 Student ID       Absent Date       Subject        

    4567           08/30/2018          M
    4567           09/22/2019          M
    8345           09/01/2019          S
    8345           03/30/2019         PE         
    8345           07/18/2017          M
    5601           01/08/2019         SS

这是所需的输出:

 Student ID       Absent Date       Subject       # of Days Since Last Absence            

    4567           08/30/2018          M                 816
    4567           09/22/2019          M                 816
    8345           09/01/2019          S                 837
    8345           03/30/2019         PE                 837        
    8345           07/18/2017          M                 837
    5601           01/08/2019         SS                 1073

感谢您的帮助。

【问题讨论】:

    标签: r dataframe datetime count time-series


    【解决方案1】:

    包裹 dplyr 和日期的max 会给你答案。 R中的当前日期是Sys.Date()

    library(dplyr)
    
    df1 %>% 
      group_by(Student_ID) %>% 
      mutate(days_since_last_absence = Sys.Date() -  max(as.Date(Absent_Date, format = "%m/%d/%Y")))
    
    
    # A tibble: 6 x 4
    # Groups:   Student_ID [3]
      Student_ID Absent_Date Subject days_since_last_absence
           <int> <chr>       <chr>   <drtn>                 
    1       4567 08/30/2018  M        816 days              
    2       4567 09/22/2019  M        816 days              
    3       8345 09/01/2019  S        837 days              
    4       8345 03/30/2019  PE       837 days              
    5       8345 07/18/2017  M        837 days              
    6       5601 01/08/2019  SS      1073 days  
    

    数据:

    df1 <- structure(list(Student_ID = c(4567L, 4567L, 8345L, 8345L, 8345L, 
    5601L), Absent_Date = c("08/30/2018", "09/22/2019", "09/01/2019", 
    "03/30/2019", "07/18/2017", "01/08/2019"), Subject = c("M", "M", 
    "S", "PE", "M", "SS")), class = "data.frame", row.names = c(NA, 
    -6L))
    

    【讨论】:

    • 我建议将max() 放在as.Date() 之外,否则“4-16-2021”将大于“11-16-2021”,并且您不依赖于字符串格式的日期,甚至“04-15-2021”都会小于“04-16-1900”
    • 更好的解释,比较一下:as.Date(max(c("04/15/2021", "04/16/1900")), format = "%m/%d/%Y") # "1900-04-16"max(as.Date(c("04/15/2021", "04/16/1900"), format = "%m/%d/%Y")) # "2021-04-15"
    • @MerijnvanTilborg,你是对的。调整好了。
    【解决方案2】:

    假设你的数据框被称为df,在base R中,试试

    df$difference<-as.numeric(difftime(Sys.Date(),as.POSIXct(paste(df[,2]),format="%m/%d/%Y"),tz="UTC"))
    

    tz 必须根据您的位置进行调整。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-01-16
      • 2020-08-06
      • 1970-01-01
      • 1970-01-01
      • 2021-05-28
      • 1970-01-01
      • 1970-01-01
      • 2016-11-12
      相关资源
      最近更新 更多