我有一个数据帧(df),它是具有以下结构的宽数据集,
ID 2015/01/01 2015/02/01 2015/03/01 2015/04/01
A1 42 42 24 32
A2 22 22 24 32
A3 12 15 19 22
A4 8 12 18 24
我厌倦了以下内容:
ts_1 <- ts(df[1:1,], start = c(2015, 05), frequency = 12)
ts_1_stl <- stl(ts_1, s.window = "periodic")
但我收到的错误为:
Error in stl(ts_1, s.window = "periodic") : only univariate series are allowed
答案 0 :(得分:1)
如果我们申请每一行(第一列是'ID',一个不需要的字符类列),我们可以apply
使用MARGIN = 1
apply(df[-1], 1, FUN = function(x) ts(x, start = c(2015, 05), frequency = 12))
对于整个数据集,我们需要unlist
ts(unlist(df[-1]), start = c(2015, 05), frequency = 12)
我们假设'df'有更多列可以有足够的观察,即“周期”工作至少有2个周期
set.seed(24)
df <- cbind(Col1 = LETTERS[1:4], as.data.frame(matrix(rnorm(31*4), ncol=31)))
res <- apply(df[-1], 1, FUN = function(x) stl(ts(x, start = c(2015, 05),
frequency = 12), s.window = "periodic"))