2014-10-20 73 views
1

我有一個df調用t_compl三列日期。如何計算不同的日期列

date_op_indl date_compl  usdato.x 
1984-11-22 1984-11-22  1983-09-07 
2004-11-16 NA    1994-10-27 
1996-09-10 1996-09-10  1982-11-09 
1986-05-24 1986-05-24  1982-11-22 
1989-08-22 1989-06-13  1983-02-11 

我想創建一個第四個變量(t_compl$time),在幾年usdato.xdate_compldate_op_indl之間的時間差。我想從date_compldate_op_indl中選擇最早的日期。

我已經試過

t_compl$time<- ifelse((t_compl$date_compl-t_compl$usdato.x)<=(t_compl$date_op_indl-t_compl$usdato.x), ((t_compl$date_compl-t_compl$usdato.x)/365.25), ((t_compl$date_op_indl-t_compl$usdato.x)/365.25)) 

因爲一些date_compl缺少我想用compl_op_indl用於計算

t_compl$time[is.na(t_compl$time)] <- ((t_compl$date_op_indl-t_compl$usdato.x)/365.25) 

,然後得到這個錯誤

Warning message: 
In t_compl$time[is.na(t_compl$time)] <- ((t_compl$date_op_indl - : 
    number of items to replace is not a multiple of replacement length 

的時間計算還對於完全錯誤3210是NA

如何在R中進行時差計算?

+0

你想要結果爲整年或年 - 月 - 日嗎? 'difftime'對你來說可能非常有用。 – 2014-10-20 16:21:06

+0

我需要時間單位的確切時間差。我選擇了幾年,因爲我有一個30年的觀察期。 – Daniel 2014-10-20 16:26:05

回答

1
DF <- read.table(text="date_op_indl date_compl  usdato.x 
1984-11-22 1984-11-22  1983-09-07 
2004-11-16 NA    1994-10-27 
1996-09-10 1996-09-10  1982-11-09 
1986-05-24 1986-05-24  1982-11-22 
1989-08-22 1989-06-13  1983-02-11", header=TRUE) 

DF[] <- lapply(DF, as.Date) 

使用pmin計算最小日期爲每個觀測(從而忽略NA值):

DF$time <- difftime(do.call(pmin, c(DF[, c("date_op_indl", "date_compl")], na.rm = TRUE)), 
        DF$usdato.x, units="days") 
# date_op_indl date_compl usdato.x  time 
# 1 1984-11-22 1984-11-22 1983-09-07 442 days 
# 2 2004-11-16  <NA> 1994-10-27 3673 days 
# 3 1996-09-10 1996-09-10 1982-11-09 5054 days 
# 4 1986-05-24 1986-05-24 1982-11-22 1279 days 
# 5 1989-08-22 1989-06-13 1983-02-11 2314 days 
+0

這一個工程,謝謝:) – Daniel 2014-10-20 20:04:03

1

下面是另一種方法。我將字符轉換爲日期,然後計算時間差。既然你說過你會以年爲單位,我有/365mutate

library(dplyr) 

mydf %>% 
    mutate_each(funs(as.Date(.))) %>% 
    mutate(time = ifelse(date_compl %in% NA, (date_op_indl - usdato.x)/365, 
        (date_compl - usdato.x)/365)) 

# date_op_indl date_compl usdato.x  time 
#1 1984-11-22 1984-11-22 1983-09-07 1.210959 
#2 2004-11-16  <NA> 1994-10-27 10.063014 
#3 1996-09-10 1996-09-10 1982-11-09 13.846575 
#4 1986-05-24 1986-05-24 1982-11-22 3.504110 
#5 1989-08-22 1989-06-13 1983-02-11 6.339726 
+0

而這一個作品以及:)偉大的有更多的選擇! – Daniel 2014-10-20 20:04:43