mydata<-data.frame(t=lubridate::ymd(c("2018-1-1","2018-1-2","2018-1-5","2018-1-6","2018-1-7","2018-1-8")),x=c(3,1,1,3,1,3))
ggplot(mydata,aes(t,x))+geom_line()
在这种情况下,我想知道x的持续时间&lt; 2,(包括&#34; 1-2,1-3,1-4,1-5,1-7&#34; 5)。如何使用R?
答案 0 :(得分:1)
使用dplyr::lag
怎么样?
# Calculate time difference to previous date
mydata$diff <- mydata$t - dplyr::lag(mydata$t);
as.numeric(sum(mydata$diff[mydata$x < 2]))
#[1] 5
或使用完整的tidyverse
方法:
require(tidyverse);
mydata %>%
mutate(diff = t - lag(t)) %>%
summarise(duration = sum(diff[x < 2]));
# duration
#1 5 days
mydata<-data.frame(
t = lubridate::ymd(c("2018-1-1", "2018-1-2", "2018-1-5", "2018-1-6", "2018-1-7", "2018-1-8")),
x = c(3, 1, 1, 3, 1, 3));