如何计算R中一列中两个日期之间的天数
How to calculate number of days between two dates in one column in R
我有以下两个数据框:
Date <- seq(as.Date("2013/1/1"), by = "day", length.out = 17)
x <-data.frame(Date)
x$discharge <- c("1000","1100","1200","1300","1400","1200","1300","1300","1200","1100","1200","1200","1100","1400","1200","1100","1400")
x$discharge <- as.numeric(x$discharge)
和
Date2 <- c("2013-01-01","2013-01-08","2013-01-12","2013-01-17")
y <- data.frame(Date2)
y$concentration <- c("1.5","2.5","1.5","3.5")
y$Date2 <- as.Date(y$Date2)
y$concentration <- as.numeric(y$concentration)
我试图使用以下代码计算从一个日期到另一个日期的天数:
y %>%
mutate(BETWEEN0=as.numeric(difftime(Date2,lag(Date2,1))),BETWEEN=ifelse(is.na(BETWEEN0),0,BETWEEN0))%>%
select(-BETWEEN0)
导致:
Date2 concentration BETWEEN
1 2013-01-01 1.5 0
2 2013-01-08 2.5 7
3 2013-01-12 1.5 4
4 2013-01-17 3.5 5
但是,我需要的是在第一个日期旁边打印的两个日期之间计算的天数等,例如
Date2 concentration BETWEEN
1 2013-01-01 1.5 7
2 2013-01-08 2.5 4
3 2013-01-12 1.5 5
4 2013-01-17 3.5 0
这意味着从 2013-01-01 到 2013-01-07 是 7 天,从 2013-01-08 到 2013-01-12 是 4 天等等
y%>%mutate(Between=as.numeric(lead(Date2,default = last(Date2))-Date2))
Date2 concentration Between
1 2013-01-01 1.5 7
2 2013-01-08 2.5 4
3 2013-01-12 1.5 5
4 2013-01-17 3.5 0
y%>%mutate(Between=as.numeric(c(diff(Date2),0)))
Date2 concentration Between
1 2013-01-01 1.5 7
2 2013-01-08 2.5 4
3 2013-01-12 1.5 5
4 2013-01-17 3.5 0
在基数 R 中:
transform(y,Between=as.numeric(c(diff(Date2),0)))
我有以下两个数据框:
Date <- seq(as.Date("2013/1/1"), by = "day", length.out = 17)
x <-data.frame(Date)
x$discharge <- c("1000","1100","1200","1300","1400","1200","1300","1300","1200","1100","1200","1200","1100","1400","1200","1100","1400")
x$discharge <- as.numeric(x$discharge)
和
Date2 <- c("2013-01-01","2013-01-08","2013-01-12","2013-01-17")
y <- data.frame(Date2)
y$concentration <- c("1.5","2.5","1.5","3.5")
y$Date2 <- as.Date(y$Date2)
y$concentration <- as.numeric(y$concentration)
我试图使用以下代码计算从一个日期到另一个日期的天数:
y %>%
mutate(BETWEEN0=as.numeric(difftime(Date2,lag(Date2,1))),BETWEEN=ifelse(is.na(BETWEEN0),0,BETWEEN0))%>%
select(-BETWEEN0)
导致:
Date2 concentration BETWEEN
1 2013-01-01 1.5 0
2 2013-01-08 2.5 7
3 2013-01-12 1.5 4
4 2013-01-17 3.5 5
但是,我需要的是在第一个日期旁边打印的两个日期之间计算的天数等,例如
Date2 concentration BETWEEN
1 2013-01-01 1.5 7
2 2013-01-08 2.5 4
3 2013-01-12 1.5 5
4 2013-01-17 3.5 0
这意味着从 2013-01-01 到 2013-01-07 是 7 天,从 2013-01-08 到 2013-01-12 是 4 天等等
y%>%mutate(Between=as.numeric(lead(Date2,default = last(Date2))-Date2))
Date2 concentration Between
1 2013-01-01 1.5 7
2 2013-01-08 2.5 4
3 2013-01-12 1.5 5
4 2013-01-17 3.5 0
y%>%mutate(Between=as.numeric(c(diff(Date2),0)))
Date2 concentration Between
1 2013-01-01 1.5 7
2 2013-01-08 2.5 4
3 2013-01-12 1.5 5
4 2013-01-17 3.5 0
在基数 R 中:
transform(y,Between=as.numeric(c(diff(Date2),0)))