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.
这意味着从2013-01-01到2013-01-07是7天,从2013-01-08到2013-01-12是4天等。
1 个解决方案
#1
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
in base R:
在基地R:
transform(y,Between=as.numeric(c(diff(Date2),0)))
#1
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
in base R:
在基地R:
transform(y,Between=as.numeric(c(diff(Date2),0)))