同时加载tidyquant与tsDyn包时,tsDyn包NNET函数示例报错求助
Hey there! This is a super common conflict issue when mixing tidyverse-aligned packages like tidyquant with time-series packages that rely on base R's stats functions. Let me break down what's happening and how to fix it:
Why the error occurs
- The
tidyquantpackage loads functions from the tidyverse (specificallydplyr), which includes its own version oflag(). - This
dplyr::lag()function is built to work with vectors, not time-series (ts) objects. tsDyn'sNNET()function depends onstats::lag()(the base R version) to handle time-series data. Whendplyr::lag()takes precedence in your environment,NNET()can't process thetsobject correctly—hence the error you're seeing.
Quick Solutions
1. Explicitly use stats::lag() in your NNET() call
When running the NNET function, specify that you want to use the base R stats version of lag instead of the dplyr one. Here's how to adjust the example code:
library(tsDyn) library(tidyquant) # Load sample data data(lynx) # Run NNET with explicit stats::lag mod <- NNET(lynx, m = 2, lag = stats::lag)
2. Temporarily override lag() for your time-series code
If you have multiple lines of tsDyn code, use rlang::local_bindings() to temporarily set lag to stats::lag within a code block. This won't affect your use of dplyr::lag outside the block:
library(tsDyn) library(tidyquant) library(rlang) data(lynx) # Temporarily use stats::lag for this code block local_bindings(lag = stats::lag) { mod <- NNET(lynx, m = 2) # Add any other tsDyn code here }
3. Avoid accidental function overwrites (alternative approach)
Load tsDyn first, then use tidyquant functions with explicit namespace calls (e.g., tidyquant::tq_get()) instead of relying on loaded functions. This prevents dplyr::lag() from overwriting the base R version entirely, though it's less convenient than the first two methods.
内容的提问来源于stack exchange,提问作者Quinn

