【问题标题】:How to convert a univariate time-series into a vector in R如何将单变量时间序列转换为 R 中的向量
【发布时间】:2021-09-01 18:13:23
【问题描述】:

imputa 函数返回单变量时间序列x.imp。 但是当我尝试使用 as.numeric 将其转换为向量时,我得到了 x.imp_v,它应该只是向量 (1, 2, 3)。

library(tidyverse)
library(imputeTS)
#> Registered S3 method overwritten by 'quantmod':
#>   method            from
#>   as.zoo.data.frame zoo

df <- tibble(c = c("a", "a", "a", "b", "b", "b"),
             d = c(1,2,3,1,2,3),
             x = c(1, NA, 3,4,5,6),
             y = c(1, 2, NA,4,5,6))

imputa <- function(df, c, v){
imp <- df %>%
  filter(c == "a") %>%
  select(d, all_of(v)) %>%
  ts(.) %>%
  na_interpolation(.)
}

x.imp <- imputa(df, "a", "x")
x.imp
#> Time Series:
#> Start = 1 
#> End = 3 
#> Frequency = 1 
#>   d x
#> 1 1 1
#> 2 2 2
#> 3 3 3
class(x.imp)
#> [1] "mts"    "ts"     "matrix"
x.imp_v <- as.numeric(x.imp)
x.imp_v
#> [1] 1 2 3 1 2 3
Created on 2021-06-16 by the reprex package (v2.0.0)

【问题讨论】:

    标签: r vector time-series


    【解决方案1】:

    imputa 的输出是带有 2 列的 matrixmatrix 只是带​​有 dim 属性的 vector。当我们执行as.numeric 时,它会调用as.vector 并因此删除属性并导致6 个元素,即每列3 个。

    str(x.imp)
     Time-Series [1:3, 1:2] from 1 to 3: 1 2 3 1 2 3
     - attr(*, "dimnames")=List of 2
      ..$ : NULL
      ..$ : chr [1:2] "d" "x"
    

    相反,只需对第二列进行子集化并应用 as.numeric 或仅应用 c

    as.numeric(x.imp[, 2])
    [1] 1 2 3
    c(x.imp[,2])
    [1] 1 2 3
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-01-03
      • 1970-01-01
      • 1970-01-01
      • 2011-02-04
      • 1970-01-01
      • 1970-01-01
      • 2018-09-06
      • 1970-01-01
      相关资源
      最近更新 更多