window.xts在parLapply中无法运行的原因是什么?
解决parLapply中window.xts报错“invalid time / time based class”的问题
报错根源在于并行函数testfun里,window的start和end参数用了纯数字(32、34),集群节点环境无法将这些数字识别为xts对象要求的Date类型,导致window.xts无法解析时间范围。
解决方法
- 明确转换时间类型:在
window调用里把数字参数转为Date类型,让集群节点能正确识别时间:
testfun <- function(input,x){ window(input, start = as.Date(32), end = as.Date(34)) + x }
- 提前定义时间变量(更清晰):在主环境先定义好时间变量,再导出到集群节点:
# 主环境定义时间变量 start_date <- as.Date(32) end_date <- as.Date(34) # 修改函数 testfun <- function(input,x){ window(input, start = start_date, end = end_date) + x }
修正后的完整代码
library(parallel) library(xts) z <- xts(11:15, as.Date(31:35)) start_date <- as.Date(32) end_date <- as.Date(34) testfun <- function(input,x){ window(input, start = start_date, end = end_date) + x } cl <- makeCluster(8) clusterEvalQ(cl, { library(xts) }) clusterExport(cl, c("testfun", "z", "start_date", "end_date")) r_1 <- parLapply( cl = cl, X = 1:8, fun = testfun, input = z) stopCluster(cl)
内容的提问来源于stack exchange,提问作者Tomta678
相关产品推荐
相关产品推荐

