我有一个模型列表,并希望返回其系数的数组(而不是列表)。(对于好奇的人来说,我正在对来自一群不同神经元的数据运行一个模型。)我想要一个数组,它是系数X神经元。如果所有模型都成功运行,则下列操作正常:
Coefs = sapply(ModelList, coef)但是,如果其中一个模型失败,coef()将返回'NULL',这与其他返回值的长度不同,我将得到一个列表而不是一个数组。:(
我的解决方案是可行的,是通用的,但却是极其笨拙的:
Coefs = sapply(ModelList, coef)
typical = Coefs[[1]] # (ought to ensure that this is not NULL!)
typical[1:length(typical)] = NA # Replace all coefficients with NA
Bad = sapply(ModelList, is.null) # Find the bad entries
for (i in which(Bad)) # For each 'NULL', (UGH! A LOOP!)
Coefs[[i]] = typical # replace with a proper entry (of NAs)
Coefs = simplify2array(Coefs) # Now I can convert it to an array有没有更好的解决办法?
谢谢!
拉里
发布于 2014-11-04 17:18:45
还是有点笨拙:
sapply(ModelList, function(x) ifelse(is.null(coef(x)), NA, coef(x))https://stackoverflow.com/questions/26741121
复制相似问题