如何用R计算时间序列数据的持续时间?

时间:2018-02-12 02:51:38

标签: r time-series

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()

enter image description here 在这种情况下,我想知道x的持续时间&lt; 2,(包括&#34; 1-2,1-3,1-4,1-5,1-7&#34; 5)。如何使用R?

1 个答案:

答案 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));