【问题标题】:How to create a Matrix out of a list of timeseries [duplicate]如何从时间序列列表中创建矩阵 [重复]
【发布时间】:2021-06-15 09:02:58
【问题描述】:

我确实有一个时间序列列表,我想从中创建一个矩阵。我的第一个想法是通过“过滤器”将列表与 dplyr 分开并合并列表列表,但我不确定这是否真的很聪明。

如果您能告诉我如何解决这个问题,那就太好了!

Example
id <- c(1,1,1,1,1,2,2,2,2,2,2)
level <-  c(100,101,100.5,102,103,100,101,103,105,103,105)
date <- as.Date(c('2021-1-1','2021-1-2','2021-1-3','2021-1-5','2021-1-6','2021-1-1','2021-1-2','2021-1-3','2021-1-4','2021-1-5','2021-1-6'))


test <- data.frame(date,id,level)


        date id level
1  2021-01-01  1 100.0
2  2021-01-02  1 101.0
3  2021-01-03  1 100.5
4  2021-01-05  1 102.0
5  2021-01-06  1 103.0
6  2021-01-01  2 100.0
7  2021-01-02  2 101.0
8  2021-01-03  2 103.0
9  2021-01-04  2 105.0
10 2021-01-05  2 103.0
11 2021-01-06  2 105.0

我想要以下内容

      date    1       2
  2021-01-01 100.0  100.0
  2021-01-02 101.0  101.0
  2021-01-03 100.5  103.0
  2021-01-04        105.0
  2021-01-05 102.0  103.0
  2021-01-06 103.0  105.0

非常感谢!

【问题讨论】:

    标签: r list dataframe


    【解决方案1】:

    使用 tidyverse 的解决方案:

    #load tidyverse
    #library(tidyverse)
    
    pivot_wider(test,
                names_sort = TRUE, # columns should be sortet by the numbers
                names_from=id,
                values_from = level,
    ) %>% 
    arrange(date) # sort by date
    
    # returns:
    # A tibble: 6 x 3
      date         `1`   `2`
      <date>     <dbl> <dbl>
    1 2021-01-01  100    100
    2 2021-01-02  101    101
    3 2021-01-03  100.   103
    4 2021-01-04   NA    105
    5 2021-01-05  102    103
    6 2021-01-06  103    105
    

    使用基础 R 的解决方案:

    reshape(test,
            idvar="date",
            timevar = "id",
            direction = "wide"
    )
    
    # Solution is close to your desired output
            date level.1 level.2
    1 2021-01-01   100.0     100
    2 2021-01-02   101.0     101
    3 2021-01-03   100.5     103
    4 2021-01-05   102.0     103
    5 2021-01-06   103.0     105
    9 2021-01-04      NA     105
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-11-14
      • 1970-01-01
      • 2013-03-29
      • 2018-11-18
      相关资源
      最近更新 更多