【问题标题】:How to make a new column containing a time series from numerical values in other columns in the same row如何根据同一行中其他列中的数值创建一个包含时间序列的新列
【发布时间】:2021-09-02 19:55:37
【问题描述】:
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.

【问题讨论】:

    标签: r time-series dplyr


    【解决方案1】:

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

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

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

    我会尝试类似的东西

    lapply(time_series, isSeasonal)
    

    【讨论】:

    • > a[1,20] [[1]] Qtr1 Qtr2 Qtr3 Qtr4 1 2 10 9 6 2 5 2 9 8 3 4 4 7 11 4 7 9 10 8 isSeasonal 正在获取 ts 对象.
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-08-02
    • 1970-01-01
    • 2020-09-10
    • 2019-09-19
    • 2021-07-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多