2016-11-15 99 views
-2

我是R新手,我試圖計算每個主題的基線日期差異。我知道如何使用difftime來計算日差異,但我無法在每個主題的循環中進行。任何幫助將不勝感激。嵌套for循環的日期差異

基本上我想從去:

ID DATE
1 2015年1月1日
1 2016年1月1日
2 2017年1月1日
3 2017年1月1日
3 2016年1月1日
3 2017年1月1日

到:

ID DATE DATEDIFF
1 2015年1月1日0
1 2016年1月1日365
2 2017年1月1日0
3 2015年1月1日0
3 2016年1月1日365
3 2017年1月1日730

回答

0

使用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  date datediff 
      
1  1 2015-01-01 0 days 
2  1 2016-01-01 365 days 
3  2 2017-01-01 0 days 
4  3 2015-01-01 0 days 
5  3 2016-01-01 365 days 
6  3 2017-01-01 731 days