【问题标题】:Split, lapply, rbind paradigm. lapply returning lists of numerics instead of date index拆分、lapply、rbind 范式。 lapply 返回数字列表而不是日期索引
【发布时间】:2020-01-20 17:05:08
【问题描述】:

我正在对 Red Sox 赛季数据集进行时间序列分析。我需要逐年拆分数据集并进行一些计算,所以我很确定我需要使用 split、lapply、rbind 范式。我将 xts 二进制(赢/输)列提供给 split 函数,到目前为止一切顺利,它返回 xts 按年份正确拆分的列表。

然后我在这个列表上运行 lapply 来计算每年赢/输的累积平均值,数字结果还可以,但是它将 xts 对象转换为数字向量,所以我丢失了我的 Date 索引。

这个问题的根源可能是什么?

谢谢!

red_sox_xts$win 的负责人。

            win
2010-04-04   1
2010-04-06   0
2010-04-07   0
2010-04-09   0
2010-04-10   1
2010-04-11   1

1 - 将其输入此函数以按年份拆分。

red_sox_seasons <- split(red_sox_xts$win, f = 'years')

输出:

[[1]]
            win
2010-04-04   1
2010-04-06   0
     .       .
     .       .
     .       .
[[2]]
            win
2011-04-01   0
2011-04-02   0
     .       .
     .       .
     .       .

2 - 接下来我将此输出提供给 lapply 函数。

red_sox_ytd <- lapply(red_sox_seasons, cummean)

输出:(这是奇怪行为开始的地方)

1.   A.1
     B.0.5
      .
      .
      .
2.   A.0
     B.0.5
      .
      .
      .

class(red_sox_ytd) 是一个列表 class(red_sox_ytd[[1]]) 是数字,但应该是 xts

这使我无法正确执行下一步:

do.call(rbind, red_sox_ytd)

【问题讨论】:

    标签: r date lapply numeric xts


    【解决方案1】:

    假设x在最后的注释中显示,我们可以使用ave按年份计算cummean

    transform(x, cummean = ave(win, format(time(x), "%Y"), FUN = cummean))
    ##            win   cummean
    ## 2010-04-04   1 1.0000000
    ## 2010-04-06   0 0.5000000
    ## 2010-04-07   0 0.3333333
    ## 2010-04-09   0 0.2500000
    ## 2010-04-10   1 0.4000000
    ## 2010-04-11   1 0.5000000
    

    另一种方法(但更长)是:

    do.call("rbind", lapply(split(x, "years"), transform, cummean = cummean(win)))
    

    注意

    Lines <- "date win
    2010-04-04   1
    2010-04-06   0
    2010-04-07   0
    2010-04-09   0
    2010-04-10   1
    2010-04-11   1"
    library(xts)
    x <- as.xts(read.zoo(text = Lines, header = TRUE, drop = FALSE))
    

    【讨论】:

    • 第一个是一个非常优雅的解决方案,我正在分解它来看看它是如何工作的。我会在一分钟内接受它作为答案。但仍然想知道我采取的方法有什么问题。我用这种方法一百万次,直到现在都没有遇到过问题。
    • 不清楚你在问什么,因为你没有提供可重现的东西。如果我们在答案中使用注释中的x,那么lapply(split(x, "years"), cummean) 会生成一个普通向量列表。
    猜你喜欢
    • 1970-01-01
    • 2014-09-16
    • 1970-01-01
    • 1970-01-01
    • 2021-07-02
    • 2016-09-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多