我正在尝试使用caret::train()
函数从具有多个响应变量的数据帧创建具有留一法式交叉验证的线性模型。我想记录转换的一些响应变量。其他一些响应变量具有NA变量。我收到以下错误:
Error in seq_len(p) : argument must be coercible to non-negative integer
In addition: Warning messages:
1: In predict.lm(trainlm, newdata = df2, type = "response") :
calling predict.lm(<fake-lm-object>) ...
2: In seq_len(p) : first element used of 'length.out' argument
浏览其他帖子,似乎是因为以下原因引起的:
我试图通过首先创建具有适当列的新数据框并使用complete.cases()
选择行来解决此问题,但是问题仍然存在。下面是我的可复制示例:
library(caret) # for train() function
set.seed(52) # to make reproducible
##Creating Fake Dataset
X1<-runif(100, 2, 21)
X2<-runif(100, 21, 40)
X3<-runif(100, 12, 18)
errors1<-rnorm(100, 0, 1)
errors2<-rnorm(100, 0, 1)
#multiple response variables
Y1<-2.31+(0.52*X1)+(0.84*X2)+(2.2*X3)+(1.5*X1*X2)+(1.6*errors1)
Y2<-5.31+(2.1*X1)+(2.2*X3)+(1.5*X1*X3)+(0.4*errors2)
##Creating an NA Value
Y2[82]<-NA
##Dataframe with all predictors and both response variables
df<-data.frame(Y1, Y2, X1, X2, X3)
##Subsetting to get rid of NA and other
df2<-subset(df[complete.cases(df),], select=-1)
##Building the model
TrCtrl<-trainControl(method="LOOCV")
trainlm<-train(log(Y2+1)~X1+X2+X3+(X1+X2)+(X1*X3)+(X2*X3)+(X1*X2*X3), method="lmStepAIC", data=df2, trControl=TrCtrl)
##Getting Prediction##
Train.Predict<-predict.lm(trainlm, newdata = df2, type = "response")
答案 0 :(得分:2)
trainlm
不是lm
类,因此predict.lm
不是正确的调用函数。
class(trainlm)
#> [1] "train" "train.formula"
使用predict
并让S3
选择适当的方法。
Train.Predict <- predict(trainlm, newdata = df2)