r - 如何从同一行的其他列中的数值创建一个包含时间序列的新列
问题描述
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.
解决方案
在这种情况下,该apply
函数返回一个列表对象,因为“对 'FUN' 的调用返回不同长度的向量”。
time_series <- apply(a[,c(2:18)] , 1 , paste_noNA)
class(time_series)
# list
我相信错误是由于isSeasonal
期望您提供ts
对象而不是列表。
我会尝试类似的东西
lapply(time_series, isSeasonal)
推荐阅读
- google-app-engine - java.lang.RuntimeException:暂存包时出错
- mysql - “显示引擎 innodb 状态”中的过时死锁信息
- asp.net-mvc - 如何获取 AppSettings 作为常量值?
- javascript - Javascript - 未找到导入
- ruby - 如果在没有 shell 的情况下运行,Ruby 会以退出代码 1 响应 TERM 退出
- javascript - VSCode - 保存时 JavaScript 文件的奇怪语法格式
- c# - Visual Studio C# 观察变量表示
- javascript - 使用浏览器控制台 (Chrome) 将表格数据从 HTML 页面导出到 CSV 文件
- node.js - NodeJs 护照验证
- postgresql - 具有已删除属性的历史表的累积计数