如何从R中的列表列表中提取元素? [英] How can I extract elements from lists of lists in R?
问题描述
我有一堆列表,其中包含列表(广义线性模型输出).我想编写一个函数,该函数将从每个列表中提取几个元素,然后将结果合并到一个数据帧中.
I have a bunch of lists containing lists within them (generalised linear model output). I want to write a function which will extract several elements from each list and then combine the results into a data frame.
我要提取modelset[[1]]$likelihood
& modelset[[1]]$fixef
,modelset[[2]]$likelihood
& modelset[[2]]$fixef
等,然后将结果合并到一个数据框中.
I want to extract modelset[[1]]$likelihood
& modelset[[1]]$fixef
, modelset[[2]]$likelihood
& modelset[[2]]$fixef
, etc, and combine the results into a data frame.
有人可以告诉我如何执行此操作吗?
Can someone give me an idea of how to do this?
很抱歉,我的问题令人困惑:我想做的事超出了我有限的编程理解.
Apologies if my question is confusing: what I am trying to do is beyond my limited programming understanding.
有关我的列表的其他信息:
Further information about my list:
modelset: Large list (16 elements, 7.3Mb)
:List of 29
..$ fixef : Named num [1:2] -1.236 -0.611
.. ..- attr(*, "names")= chr [1:2] "(Intercept)" "SMIstd"
..$ likelihood :List of 4
.. ..$ hlik: num 238
.. ..$ pvh : num 256
.. ..$ pbvh: num 260
.. ..$ cAIC: num 567
...etc
推荐答案
为了优雅地解决此问题,您需要了解可以使用['…']
而不是$…
来访问列表元素(但您将获得一个列表)返回而不是单个元素.
In order to solve this elegantly you need to understand that you can use ['…']
instead of $…
to access list elements (but you will get a list back instead of an individual element).
因此,如果要获取元素likelihood
和fixef
,则可以编写:
So if you want to get the elements likelihood
and fixef
, you can write:
modelset[[1]][c('likelihood', 'fixef')]
现在,您要为modelset
中的每个元素执行此操作.这就是 lapply
的作用:
Now you want to do that for each element in modelset
. That’s what lapply
does:
lapply(modelset, function (x) x[c('likelihood', 'fixef')])
这行得通,但不是很像R.
This works, but it’s not very R-like.
在R中,您几乎可以看到所有内容是一个函数. […]
正在调用名为[
的函数(但由于[
是R的特殊符号,因此需要在反引号中引用:`[`
).因此,您可以这样写:
You see, in R, almost everything is a function. […]
is calling a function named [
(but since [
is a special symbol for R, in needs to be quoted in backticks: `[`
). So you can instead write this:
lapply(modelset, function (x) `[`(c('likelihood', 'fixef')])
哇,那根本不是很可读.但是,我们现在可以删除包装的匿名function (x)
,因为在内部我们只是在调用另一个函数,然后将多余的参数移到lapply
的最后一个参数:
Wow, that’s not very readable at all. However, we can now remove the wrapping anonymous function (x)
, since inside we’re just calling another function, and move the extra arguments to the last parameter of lapply
:
lapply(modelset, `[`, c('likelihood', 'fixef'))
这行之有效并且是优雅的R代码.
This works and is elegant R code.
让我们退后一步,重新检查我们在这里所做的事情.实际上,我们有一个看起来像这样的表达式:
Let’s step back and re-examine what we did here. In effect, we had an expression which looked like this:
lapply(some_list, function (x) f(x, y))
此呼叫可以改写为
lapply(some_list, f, y)
我们正是通过somelist = modelset
,f = `[`
和y = c('likelihood', 'fixef')
做到了这一点.
We did exactly that, with somelist = modelset
, f = `[`
and y = c('likelihood', 'fixef')
.
这篇关于如何从R中的列表列表中提取元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!