How to calculate number of days between two dates in one column in R

試著忘記壹切 提交于 2019-12-13 03:29:32

问题


I have the following two data frames:

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)

And

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)

I was trying to calculate the number of days from one date to the other with the following code:

y %>%
    mutate(BETWEEN0=as.numeric(difftime(Date2,lag(Date2,1))),BETWEEN=ifelse(is.na(BETWEEN0),0,BETWEEN0))%>%
    select(-BETWEEN0)

Resulting in:

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

However, what I would need is the number of days calculated between two dates printed next to the first date etc, e.g.

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

That means that from 2013-01-01 to 2013-01-07 are 7 days, from 2013-01-08 to 2013-01-12 are 4 days etc.


回答1:


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

in base R:

 transform(y,Between=as.numeric(c(diff(Date2),0)))


来源:https://stackoverflow.com/questions/51148341/how-to-calculate-number-of-days-between-two-dates-in-one-column-in-r

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!