I’m using rpy2 in Python to call R's forecast::stlm() function from within a custom wrapper function defined in R. My goal is to fit a seasonal time series model (STL + ARIMA) on a univariate time series without any external regressors (xreg).
Here is a minimal working version of my Python code:
import pandas as pd
import numpy as np # For potential NaN generation in example data
import rpy2.robjects as ro
from rpy2.robjects.packages import STAP, importr
from rpy2.robjects import pandas2ri
from rpy2.robjects.conversion import localconverter
from rpy2.robjects import FloatVector, IntVector # Direct import for clarity
from rpy2.rinterface import NULLType
fn_def = """
fit <- function(y, FUN, ...) {
arguments <- list(...)
names(arguments) <- gsub("_", ".", names(arguments))
arguments <- c(list(y = y), arguments)
model.fit <- tryCatch({
do.call(FUN, arguments, quote = TRUE)
}, error = function(err) {
stop(err)
})
print( summary(model.fit) )
return(model.fit)
}
"""
error_wrapper = STAP(fn_def, "STAP_fun")
ro.r('library(forecast)')
import rpy2.robjects as robjects
r_ts_function = robjects.r('ts')
y_ts = r_ts_function(pd.Series([1,2,4,2,4,6,3,4,7,6,4,4,7,8,5,8,9,5,6]).values, frequency=6)
out =error_wrapper.fit(y= y_ts,
FUN = ro.r['stlm'],
method = "ets"
)
When I try to run the above code, I am getting below error.
RRuntimeError: Error in if (ncol(x) == 1L) { : missing value where TRUE/FALSE needed
How do I safely call stlm() from Python via rpy2 without triggering ncol(x) errors when xreg is not needed?
Note: I am executing this code on the synapse notebook.
Thanks in advance.