我的时间序列很短
Semester E
2015-01 828
2015-05 277
2015-08 2105
2016-01 1926
2016-05 619
2016-08 2389
2017-01 2522
2017-05 598
2017-08 2541
2018-01 2200
2018-05 644
2018-08 2541
2019-01 2031
我想使用R中的window函数将其转换到2018年(请保留到2019年)
决赛桌是这样:
1 2 3
2015 828 277 2105
2016 1926 619 2389
2017 2522 598 2541
2018 2200 644 2541
如何使用窗口功能做到这一点?
答案 0 :(得分:0)
一种选择是提取“年份”,然后提取spread
library(dplyr)
library(lubridate)
library(tidyr)
df1 %>%
group_by(Year = year(dmy(Term))) %>%
mutate(rn = row_number()) %>%
select(-Term) %>%
spread(rn, E)
# A tibble: 5 x 4
# Groups: Year [5]
# Year `1` `2` `3`
# <dbl> <int> <int> <int>
#1 2015 828 277 2105
#2 2016 1926 619 2389
#3 2017 2522 598 2541
#4 2018 2200 644 2541
#5 2019 2301 NA NA
或使用base R
Year <- format(as.Date(df1$Term, "%d/%m/%Y"), "%Y")
s1 <- ave(seq_along(Year), Year, FUN = seq_along)
xtabs(df1$E ~ Year + s1)
df1 <- structure(list(Term = c("1/1/2015", "5/1/2015", "8/1/2015",
"1/1/2016", "5/1/2016", "8/1/2016", "1/1/2017", "5/1/2017", "8/1/2017",
"1/1/2018", "5/1/2018", "8/1/2018", "1/1/2019"), E = c(828L,
277L, 2105L, 1926L, 619L, 2389L, 2522L, 598L, 2541L, 2200L, 644L,
2541L, 2301L)), class = "data.frame", row.names = c(NA, -13L))