我在控制输入预测函数的对象类型时遇到问题 . 这是我生成 glm
对象的简化函数 .
fitOneSample <- function(x,data,sampleSet)
{
#how big of a set are we going to analyze? Pick a number between 5,000 & 30,000, then select that many rows to study
sampleIndices <- 1:5000
#now randomly pick which columns to study
colIndices <- 1:10
xnames <- paste(names(data[,colIndices]),sep = "")
formula <- as.formula(paste("target ~ ", paste(xnames,collapse = "+")))
glm(formula,family=binomial(link=logit),data[sampleIndices,])
}
myFit <- fitOneSample(1,data,sampleSet)
fits <- sapply(1:2,fitOneSample,data,sampleSet)
all.equal(myFit,fits[,1]) #different object types
#this works
probability <- predict(myFit,newdata = data)
#this doesn't
probability2 <- predict(fits[,1],newdata = data)
# Error in UseMethod("predict") :
# no applicable method for 'predict' applied to an object of class "list"
如何访问 fits[,1]
中的列,以便我可以使用预测函数获得与 myFit
相同的结果?
1 回答
我想我现在能够恢复你的状况了 .
这使用内置数据集
trees
作为示例,拟合三个线性模型:由于我们使用了
sapply
,并且每次迭代都返回相同的lm
对象或长度为12的列表,因此结果将简化为12 * 3
矩阵:矩阵索引
fits[, 1]
有效 .如果你检查
str(fits[, 1])
,它几乎看起来像一个普通的lm
对象 . 但如果你进一步检查:Em? It does not have "lm" class! 因此,当您调用泛型函数
predict
时,S3
dispatch方法将失败:This can be seen as a good example that sapply is destructive. 我们想要
lapply
,或者至少是sapply(..., simplify = FALSE)
:lapply
的结果更容易理解 . 它是一个长度为3的列表,其中每个元素都是lm
对象 . 我们可以通过fits[[1]]
访问第一个模型 . 现在一切都会奏效:你可以修改你的代码