如何解决TSLM警告:参数必须可强制转换为非负整数
问题描述
尝试在谷歌(GOOG)2018年股票收盘价时间序列中分析多重季节性,但使用TSLM()拟合趋势+季节模型时,即便将收盘价从double转为整数,仍触发警告:
1 error encountered for TSLM(Close ~ trend() + season())
[1] argument must be coercible to non-negative integer
数据无NA值且所有收盘价为正数,不使用管道符也会出现相同警告。
原始代码:
rm(list = ls()) require(fpp3) goog<-gafa_stock|>filter(Symbol=="GOOG",year(Date)==2018) close<-goog|>select(Close) # just get close sum(is.na(close)) # no na's min(close$Close) # min is positive fitClose <- close |> model(TSLM(Close ~ trend() + season())) # complains # Warning message: # 1 error encountered for TSLM(Close ~ trend() + season()) # [1] argument must be coercible to non-negative integer c<-close |> mutate(Close=as.integer(Close)) # convert to integer #autoplot(c) #close|>mutate(Close = Close / first(Close)) fit <- c |> model(TSLM(Close ~ trend() + season())) # still complains report(fit)
编辑1:不使用管道符的代码同样报错:
fitClose <- model(close,TSLM(Close ~ trend() + season())) # complains
解决方案
警告的核心原因是:你只保留了Close列,丢失了作为时间索引的Date列,导致close不再是tsibble(时间序列数据框),season()和trend()函数需要依赖时间索引计算周期和趋势项,没有索引就无法正常工作。
修复步骤:
- 必须保留时间索引列
Date,确保输入数据是tsibble类型(gafa_stock本身就是tsibble,过滤后只要不丢失索引列就没问题)
修改后的代码:
rm(list = ls()) require(fpp3) # 过滤数据时默认保留Date列,无需额外操作 goog <- gafa_stock |> filter(Symbol == "GOOG", year(Date) == 2018) sum(is.na(goog$Close)) # 确认无NA min(goog$Close) # 确认数值为正 # 直接用带时间索引的tsibble拟合模型 fitClose <- goog |> model(TSLM(Close ~ trend() + season())) report(fitClose)
如果确实只需要Close列,也要保留Date作为索引:
# 保留Date和Close列,确保仍是tsibble close_ts <- goog |> select(Date, Close) fitClose <- close_ts |> model(TSLM(Close ~ trend() + season()))
补充说明:
fpp3包的所有建模函数都要求输入是tsibble,必须包含明确的时间索引列season()函数会根据时间索引的频率自动识别季节周期(比如日度数据的周周期、年度周期),没有索引就无法计算- 转换收盘价为整数完全没必要,这个操作和警告无关,属于无效尝试
内容的提问来源于stack exchange,提问作者Ray Tayek
相关产品推荐
相关产品推荐

