且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何从R中的列表列表中提取元素?

更新时间:2022-05-27 22:05:03

为了优雅地解决此问题,您需要了解可以使用['…']而不是$…来访问列表元素(但您将获得一个列表)返回而不是单个元素.

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).

因此,如果要获取元素likelihoodfixef,则可以编写:

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 = modelsetf = `[`y = c('likelihood', 'fixef')做到了这一点.

We did exactly that, with somelist = modelset, f = `[` and y = c('likelihood', 'fixef').