提取嵌套列表中的项目

Extract items in nested lists

我有一个问题: 我根据温度(自变量)使用具有五个物种的发育时间(因变量)的数据框 使用 "by" 函数,我计算了所有五个物种的 lm

by(dados, dados$Especie, function(dados) lm(dados$Tempo ~ dados$Temp, data = dados)

结果我得到了嵌套在其他列表中的列表,如您所见

List of 5
 $ C.albiceps   :List of 12
  ..$ coefficients : Named num [1:2] 262.78 -1.76
  .. ..- attr(*, "names")= chr [1:2] "(Intercept)" "dados$Temp"
  ..$ residuals    : Named num [1:41] -4.157 -2.394 -0.631 1.131 2.894 ...
  .. ..- attr(*, "names")= chr [1:41] "1" "2" "3" "4" ...
  ..$ effects      : Named num [1:41] -1344.031 -133.548 0.235 1.977 3.72 ...
  .. ..- attr(*, "names")= chr [1:41] "(Intercept)" "dados$Temp" "" "" ...
  ..$ rank         : int 2

这是一个包含 5 个元素的列表(每个物种一个),每个物种是一个包含 12 个元素的列表(来自 lm 函数)。因此,5 个列表中的 5 个 12 个列表。

现在,我的问题是: 我想从我的系数中提取值并将它们相加。所以我得到了 List$speciesName$coefficients[2] 我想提取每个值($coefficients 的第二项,对于每个物种),我还想将它保存在一个向量中(以便用它计算索引)。

有什么有用的提示吗?

您可以使用 apply 函数遍历模型并使用 coef 提取系数。

## Example
mods <- by(mtcars, mtcars$cyl, function(x) lm(mpg ~ disp, data=x))

## Sum up all the second coefficients
sum(sapply(mods, function(x) coef(x)[[2]]))