2014-11-04 52 views
1

我的模型的列表,并希望返回其系数的阵列(不是列表)。 (对于好奇,我从一堆不同的神经元的运行数据的单一模式,我想一个数组,它是系数X的神经元。)如果所有车型成功运行以下工作正常:使用sapply(,,简化= TRUE)

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 

有没有更好的解决办法

感谢

拉里

回答

1

仍然是一个!有点笨拙:

sapply(ModelList, function(x) ifelse(is.null(coef(x)), NA, coef(x))