gpt4 book ai didi

r - 从数据帧生成时间序列列表

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

我有一个看起来像这样的数据框:

# A tibble: 6 x 4
# Groups: IND_LOC [1]
year_month total_this_month mean_this_month IND_LOC
<S3: yearmon> <dbl> <dbl> <fct>
1 Jan 2013 3960268. 360024. 8_9
2 Feb 2013 3051909. 277446. 8_9
3 Mar 2013 3504636. 318603. 8_9
4 Apr 2013 3234451. 294041. 8_9
5 May 2013 3409146. 284096. 8_9
6 Jun 2013 3619219. 301602. 8_9

最后一列“IND_LOC”有 89 个唯一值(1_1、1_2 ... 8_9)

我想生成与这些“IND_LOC”值相对应的时间序列列表,使其具有以下结构(这只是具有不同数据集的示例,将“$1_1”替换为“$Germany”等):
> str(time_series)
List of 9
$ Germany : Time-Series [1:52] from 1960 to 2011: 684721 716424 749838 ...
$ Singapore : Time-Series [1:52] from 1960 to 2011: 7208 7795 8349 ...
$ Finland : Time-Series [1:37] from 1975 to 2011: 85842 86137 86344 ...

非常感谢您对此的任何帮助!

最佳答案

另一种选择,使用 splitlapply ;并使用 zoo作为转换的 helper ts .

dat <- read.csv(text="year_month,total_this_month,mean_this_month,IND_LOC
Jan 2013,3960268,360024,8_9
Feb 2013,3051909,277446,8_9
Mar 2013,3504636,318603,8_9
Apr 2013,3234451,294041,8_9
May 2013,3409146,284096,8_9
Jun 2013,3619219,301602,8_9
Jan 2013,3960268,360024,9_9
Feb 2013,3051909,277446,9_9
Mar 2013,3504636,318603,9_9
Apr 2013,3234451,294041,9_9
May 2013,3409146,284096,9_9
Jun 2013,3619219,301602,9_9")
dat$year_month <- as.yearmon(dat$year_month)

library(zoo)
time_series <- lapply(split(dat, dat$IND_LOC),
function(x) as.ts(zoo(x$total_this_month, x$year_month)))
str(time_series)
# List of 2
# $ 8_9: Time-Series [1:6] from 1 to 6: 3234451 3051909 3960268 3619219 3504636
# $ 9_9: Time-Series [1:6] from 1 to 6: 3234451 3051909 3960268 3619219 3504636
sapply(time_series, frequency)
# 8_9 9_9
# 12 12

关于r - 从数据帧生成时间序列列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50422437/

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