fable::VAR中:运算符传参失效及批量变量传递方法问询
问题:fable包VAR函数中vars()使用
:运算符报错的原因及批量传参方法 问题现象
在使用fable包的VAR函数时,用英文逗号分隔变量传入vars()能正常运行,但改用:运算符时会触发警告,输出结果完全不符合预期。
示例代码
library(fable) library(tidyverse) lung_deaths <- cbind(mdeaths, fdeaths) %>% as_tsibble(pivot_longer = FALSE) lung_deaths %>% model(VAR(vars(mdeaths:fdeaths) ~ AR(1))) %>% tidy()
触发的警告
Warning message: In mdeaths:fdeaths : numerical expression has 72 elements: only the first used
异常输出
# A tibble: 2 × 7 .model term .response estimate std.error statistic p.value <chr> <chr> <chr> <dbl> <dbl> <dbl> <dbl> 1 VAR(vars(mdeaths:fdeaths) ~ AR(1)) lag(mdeaths:fdeaths,1) mdeaths:fdeaths 1.00 9.52e-17 1.05e16 0 2 VAR(vars(mdeaths:fdeaths) ~ AR(1)) constant
逗号分隔的正确结果
# A tibble: 6 × 7 .model term .response estimate std.error statistic p.value <chr> <chr> <chr> <dbl> <dbl> <dbl> <dbl> 1 VAR(vars(mdeaths, fdeaths) ~ AR(1)) lag(mdeaths,1) mdeaths 0.872 0.362 2.41 0.0185 2 VAR(vars(mdeaths, fdeaths) ~ AR(1)) lag(fdeaths,1) mdeaths -0.281 0.871 -0.322 0.748 3 VAR(vars(mdeaths, fdeaths) ~ AR(1)) constant mdeaths 337. 126. 2.68 0.00925 4 VAR(vars(mdeaths, fdeaths) ~ AR(1)) lag(mdeaths,1) fdeaths 0.299 0.150 2.00 0.0500 5 VAR(vars(mdeaths, fdeaths) ~ AR(1)) lag(fdeaths,1) fdeaths 0.0253 0.361 0.0700 0.944 6 VAR(vars(mdeaths, fdeaths) ~ AR(1)) constant fdeaths 93.5 52.2 1.79 0.0776
原因分析
R语言中:运算符的核心作用是生成数值序列(比如1:5生成1到5的整数序列)。当你在vars()里写mdeaths:fdeaths时,R会把这两个时间序列对象当成数值向量处理,尝试生成从mdeaths第一个元素到fdeaths第一个元素的序列——但这两个变量都是长度为72的时间序列,R会抛出警告“只使用第一个元素”,最终vars()拿到的不是你想要的两个变量列表,而是一个错误的单变量序列,导致VAR模型错误地将其当作单个变量建模,出现异常输出。
而用英文逗号分隔变量(vars(mdeaths, fdeaths))是vars()函数设计的多变量传递方式,能正确识别每个独立变量,因此模型运行正常。
批量传递变量的替代方法
如果变量数量多,不想逐个罗列,可以用以下几种方法:
1. 传入所有变量:everything()
如果要把数据框里的所有变量都传入模型,直接用everything():
lung_deaths %>% model(VAR(vars(everything()) ~ AR(1))) %>% tidy()
2. 按变量名匹配:starts_with()/ends_with()/contains()
如果变量名有规律,比如都以“death”结尾,或者包含特定字符,可以用这些选择器:
# 匹配所有以"deaths"结尾的变量 lung_deaths %>% model(VAR(vars(ends_with("deaths")) ~ AR(1))) %>% tidy()
3. 用变量名向量配合all_of()
先定义要传入的变量名向量,再用all_of()传入vars():
var_names <- c("mdeaths", "fdeaths") lung_deaths %>% model(VAR(vars(all_of(var_names)) ~ AR(1))) %>% tidy()
内容的提问来源于stack exchange,提问作者Matt R
相关产品推荐
相关产品推荐

