【问题标题】:Reorganizing dataframe for time-series using reshape2 (melt and cast)使用 reshape2 (melt and cast) 为时间序列重组数据帧
【发布时间】:2013-11-23 21:20:17
【问题描述】:

我正在尝试获取数据框的一些片段并重新调整它们,以便它们适合使用 xtszoo 之类的包进行时间序列分析。为此(据我所知),我只需要一个时间序列矩阵,其中包含相关变量的值,以广泛的形式设置。

看来reshape2 包中的meltcast 将是执行此操作的方法,我正在使用此处找到的相同方法:https://stats.stackexchange.com/questions/7439/how-to-change-data-between-wide-and-long-formats-in-r ...但我遇到了麻烦.

假设这是数据集:

df <- structure(list(Date = structure(c(15461, 15462, 15463, 15461, 
15462, 15461, 15462, 15463, 15461, 15462, 15461, 15462, 15461, 
15462, 15463), class = "Date"), Company = structure(c(2L, 2L, 
2L, 2L, 2L, 3L, 3L, 3L, 3L, 3L, 1L, 1L, 1L, 1L, 1L), .Label = c("Fakeco", 
"Globcorp", "Renco"), class = "factor"), Region = structure(c(2L, 
2L, 2L, 3L, 3L, 3L, 3L, 3L, 1L, 1L, 3L, 3L, 2L, 2L, 2L), .Label = c("amer", 
"asia", "euro"), class = "factor"), Revenue = c(141L, 467L, 168L, 
359L, 220L, 124L, 303L, 196L, 264L, 461L, 149L, 472L, 287L, 308L, 
333L)), .Names = c("Date", "Company", "Region", "Revenue"), row.names = c(NA, 
-15L), class = "data.frame")

最终,我希望使用唯一的日期条目组织数据,每列 一家区域公司,并将收入作为值。

我的第一个猜测是做类似的事情

1) 创建一个变量,它是 Company 和 Region 的组合,以便每个组合 可以是一列:

df$coreg <- do.call(paste, c(df[c("Company", "Region")], sep= "_"))

2) 使用plyr 围绕这个新变量重新组织

dfply <- ddply(df, c("Date","coreg"),
    function(df) c(Revenue = sum(df[,4])))

3) 使用reshape2 中的meltcast 函数重新组织时间序列的数据 分析。

one <- melt(dfply, id=c("Date","coreg"))

two <- dcast(one, Date ~ coreg)

但是有没有更直接的方法可以做到这一点?这似乎是一个非常迂回的方式 进行了几次切换和数据聚合,我觉得我没有正确利用 meltcast...

【问题讨论】:

    标签: r reshape


    【解决方案1】:

    这是您要查找的格式吗?

    dcast(df, Date ~ Region + Company, value.var = "Revenue")
    
    #         Date amer_Renco asia_Fakeco asia_Globcorp euro_Fakeco euro_Globcorp euro_Renco
    # 1 2012-05-01        264         287           141         149           359        124
    # 2 2012-05-02        461         308           467         472           220        303
    # 3 2012-05-03         NA         333           168          NA            NA        196
    

    【讨论】:

    • 好吧,我不知道可以从一行 dcast 代码完成整个操作;这正是我要找的!
    【解决方案2】:

    试试这个,忽略警告,或者使用suppressWarnings(read.zoo(df, split = 2:3))

    library(zoo)
    z <- read.zoo(df, split = 2:3)
    

    【讨论】:

    • 我第一次看到split 参数在起作用。 +1。 read.zoo确实是个很棒的功能!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-05-04
    • 2020-02-19
    • 2019-01-22
    • 1970-01-01
    • 2021-02-26
    • 2020-06-12
    • 2021-07-26
    相关资源
    最近更新 更多