【问题标题】:Nested for loops for date differences用于日期差异的嵌套 for 循环
【发布时间】:2016-11-15 23:13:57
【问题描述】:

我是 R 新手,我正在尝试计算每个主题与基线的日期差异。我知道如何使用 difftime 计算日差,但我在为每个主题循环执行它时遇到了麻烦。任何帮助将不胜感激。

基本上我想从:

身份证日期
1 1.1.2015
1 1.1.2016
2 1.1.2017
3 1.1.2017
3 1.1.2016
3 1.1.2017

到:

ID DATE DATEDIFF
1 1.1.2015 0
1 1.1.2016 365
2 1.1.2017 0
3 1.1.2015 0
3 1.1.2016 365
3 1.1.2017 730

【问题讨论】:

    标签: r date for-loop


    【解决方案1】:

    使用lubridate解析日期,使用dplyr计算新列:

    library(lubridate)
    df <- data.frame(
      id = c(1,1,2,3,3,3),
      date = c('1.1.2015','1.1.2016','1.1.2017','1.1.2015','1.1.2016','1.1.2017'))
    # parse dates as DayMonthYear
    df$date <- dmy(df$date)
    # calculate the difference to the oldest date in each group
    # mutate is called once for each group, so you could use an
    # arbitrary expression to calculate your new column only with
    # the data for this group
    df %>% group_by(id) %>% mutate(datediff = date-min(date))
    

    结果:

     id 日期 datediff
              
    1 1 2015-01-01 0 天
    2 1 2016-01-01 365 天
    3 2 2017-01-01 0 天
    4 3 2015-01-01 0 天
    5 3 2016-01-01 365 天
    6 3 2017-01-01 731 天

    【讨论】:

      猜你喜欢
      • 2021-07-18
      • 2021-01-05
      • 2016-06-02
      • 1970-01-01
      • 1970-01-01
      • 2013-08-19
      • 1970-01-01
      • 1970-01-01
      • 2021-12-11
      相关资源
      最近更新 更多