How to convert a univariate time-series into a vector in R

Viewed 153

The imputa function returns a univariate time-series x.imp. But when I try to convert it into a vector using as.numeric I get x.imp_v which should be only the vector (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)
1 Answers

The output of imputa is a matrix with 2 columns and matrix is just a vector with dim attributes. When we do the as.numeric, it calls the as.vector and thus remove the attributes and result in 6 elements i.e. 3 from each column.

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"

Instead, just subset the second column and apply the as.numeric or just c

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