我在控制输入预测函数的对象类型时遇到问题。这是我生成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
相同的结果?
答案 0 :(得分:1)
我想我现在能够恢复你的状况。
fits <- sapply(names(trees),
function (y) do.call(lm, list(formula = paste0(y, " ~ ."), data = trees)))
这使用内置数据集trees
作为示例,拟合三个线性模型:
Girth ~ Height + Volume
Height ~ Girth + Volume
Volume ~ Height + Girth
由于我们使用了sapply
,并且每次迭代都返回相同的lm
对象或长度为12的列表,因此结果将简化为12 * 3
矩阵:
class(fits)
# "matrix"
dim(fits)
# 12 3
矩阵索引fits[, 1]
有效。
如果您检查str(fits[, 1])
,它几乎看起来像一个普通的lm
对象。但如果你进一步检查:
class(fits[, 1])
# "list"
<强> EM?它没有“lm”类!因此,当您调用泛型函数S3
时,predict
调度方法将失败:
predict(x)
#Error in UseMethod("predict") :
# no applicable method for 'predict' applied to an object of class "list"
这可以看作sapply
具有破坏性的好例子。我们想要lapply
,或者至少sapply(..., simplify = FALSE)
:
fits <- lapply(names(trees),
function (y) do.call(lm, list(formula = paste0(y, " ~ ."), data = trees)))
lapply
的结果更容易理解。它是长度为3的列表,其中每个元素都是lm
对象。我们可以通过fits[[1]]
访问第一个模型。现在一切都会奏效:
class(fits[[1]])
# "lm"
predict(fits[[1]])
# 1 2 3 4 5 6 7 8
# 9.642878 9.870295 9.941744 10.742507 10.801587 10.886282 10.859264 10.957380
# 9 10 11 12 13 14 15 16
#11.588754 11.289186 11.946525 11.458400 11.536472 11.835338 11.133042 11.783583
# 17 18 19 20 21 22 23 24
#13.547349 12.252715 12.603162 12.765403 14.002360 13.364889 14.535617 15.016944
# 25 26 27 28 29 30 31
#15.628799 17.945166 17.958236 18.556671 17.229448 17.131858 21.888147
您可以通过
修复代码fits <- lapply(1:2,fitOneSample,data,sampleSet)
probability2 <-predict(fits[[1]],newdata = data)