gpt4 book ai didi

r - 将时间序列转换为数据帧并返回

转载 作者:行者123 更新时间:2023-12-03 14:47:21 24 4
gpt4 key购买 nike

时间序列的输出看起来像一个数据帧:

ts(rnorm(12*5, 17, 8), start=c(1981,1), frequency = 12)

Jan Feb Mar Apr May Jun Jul ...
1981 14.064085 21.664250 14.800249 -5.773095 16.477470 1.129674 16.747669 ...
1982 23.973620 17.851890 21.387944 28.451552 24.177141 25.212271 19.123179 ...
1983 19.801210 11.523906 8.103132 9.382778 4.614325 21.751529 9.540851 ...
1984 15.394517 21.021790 23.115453 12.685093 -2.209352 28.318686 10.159940 ...
1985 20.708447 13.095117 32.815273 9.393895 19.551045 24.847337 18.703991 ...


将其转换为具有Jan,Feb,Mar ...列和1981、1982等行的数据框,然后返回。最优雅的方法是什么?

最佳答案

这有两种方法。第一种方法为要创建的矩阵创建暗名,然后将数据串出到矩阵中,将其转置并将其转换为数据帧。第二种方法创建一个由年和月变量组成的by列表,并在之后使用tapply转换为数据框并添加名称。

# create test data
set.seed(123)
tt <- ts(rnorm(12*5, 17, 8), start=c(1981,1), frequency = 12)


1)矩阵。此解决方案要求我们连续整整一年

dmn <- list(month.abb, unique(floor(time(tt))))
as.data.frame(t(matrix(tt, 12, dimnames = dmn)))


如果我们不在乎漂亮的名字,那就只是 as.data.frame(t(matrix(tt, 12)))

我们可以使用@thelatemail的注释用以下更简单的行替换 dmn<-行:

dmn <- dimnames(.preformat.ts(tt))


2)轻按。以下是使用 tapply的更通用的解决方案:

Month <-  factor(cycle(tt), levels = 1:12, labels = month.abb)
tapply(tt, list(year = floor(time(tt)), month = Month), c)


注意:假设 X是以上任何一种解决方案,则可以反过来解释。然后尝试:

ts(c(t(X)), start = 1981, freq = 12)


更新资料

改进来自以下@latemail的评论。

关于r - 将时间序列转换为数据帧并返回,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5331901/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com