如何从同一行中其他列的数值创建一个包含时间序列的新列

时间:2021-06-18 03:46:10

标签: r time-series mutate

library(seastests) 
        
paste_noNA <- function(x) {
      ts(x[!is.na(x)],frequency=12)
}
        
a <- data.frame(a=c(1,2),b=c(2,5),c=c(10,2),
     d=c(9,22),e=c(6,3),f=c(5,7), 
     g=c(2,12),h=c(9,7),i=c(8,8),
     j=c(4,21),k=c(NA,7),l=c(4,2),
     m=c(7,3),n=c(11,8),o=c(7,8),  
     p=c(9,6),q=c(10,9),r=c(8,9),s=c("f","h"))
            
a$time_series<-apply( a[,c(2:18)] , 1 , paste_noNA )
<块引用>
> a
  a b  c  d e f  g h i  j  k l m  n o p  q r s
1 1 2 10  9 6 5  2 9 8  4 NA 4 7 11 7 9 10 8 f
2 2 5  2 22 3 7 12 7 8 21  7 2 3  8 8 6  9 9 h
                                           time_series
1    2, 10, 9, 6, 5, 2, 9, 8, 4, 4, 7, 11, 7, 9, 10, 8
2 5, 2, 22, 3, 7, 12, 7, 8, 21, 7, 2, 3, 8, 8, 6, 9, 9
a<-a %>% mutate(iss=isSeasonal(time_series))
    
    Error: Problem with `mutate()` column `iss`.
    i `iss = isSeasonal(time_series)`.
    x Do not know the frequency of the time series.
    Run `rlang::last_error()` to see where the error occurred.

考虑上面的代码。我试图在“time_series”列中输入第 2 到 18 列中作为时间序列处理的数值的串联。然后我想检查时间序列的季节性,但我得到了上面代码块末尾所述的错误,尽管 paste_noNA 函数已经将串联转换为时间序列。有人可以帮忙吗?

我也试过

a<-a %>% mutate(time_series=ts(time_series,frequency=12)) %>% 
  mutate(iss=isSeasonal(time_series))

但得到了错误

Error: Problem with `mutate()` column `time_series`.
i `time_series = ts(time_series, frequency = 12)`.
x `time_series` must be a vector, not a `ts` object.
Run `rlang::last_error()` to see where the error occurred.

1 个答案:

答案 0 :(得分:1)

在这种情况下,apply 函数返回一个列表对象,因为“对‘FUN’的调用返回不同长度的向量”。

time_series <- apply(a[,c(2:18)] , 1 , paste_noNA)
class(time_series)
# list

我认为错误是由于 isSeasonal 期望您提供一个 ts 对象而不是列表。

我会尝试类似的东西

lapply(time_series, isSeasonal)
相关问题