本文介绍了列表的子集的子集的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在R中,我有一个由12个子列表组成的列表,每个列表本身都由5个子列表组成,如下所示:

In R, I have a list, composed of 12 sublists, each themselves composed of 5 subsublists as follow

列表和子列表

在此示例中,我要为每个子列表提取信息"MSD".

In this example, I want to extract the info "MSD", for each of these sublists.

我可以使用

lapply(letters, '[[', "statistics")

效果很好.对于每个列表,它为我提供了子列表统计"中包含的所有值但是,我想将其下调一点,因为我对MSerror,Df等其他数据不感兴趣.仅MSD

That worked well. It gave me all the values contained in the sublist "statistics", for each listHowever, I want to go one level down of that, as I am not interested in the other data such as MSerror, Df, ..... Only MSD

我尝试了

lapply(letters, '[[', "statistics", "MSD")

和许多其他没有成功的人.

and many others without success.

如果我只想要第一个子列表,它将与

If I wanted only the first sublist, it will work with

letters[[1]][["statistics"]][["MSD"]]

但是,我必须这样做:

letters[[1]][["statistics"]][["MSD"]]
letters[[2]][["statistics"]][["MSD"]]
letters[[3]][["statistics"]][["MSD"]]

我想暂时避免.

感谢您的帮助.

推荐答案

我们可以使用lambda/匿名函数

We can use a lambda/anonymous function

lapply(letters, function(x) x[["statistics"]][["MSD"]])

此功能的好处在于,如果我们有多个嵌套元素,则不必调用 n lapply ,它应该更快

The benefit of this function is that if we have multiple nested elements, we don't have to call n lapply and should be faster

或使用 map

library(tidyverse)
map(letters, ~ .x[["statistics"]][["MSD"]])

此外,关于这样的说法,即如果列表中没有某些元素,

Also, regarding the claim that this wouldn't work if there are not some elements in the list,

set.seed(24)
lst1 <- replicate(3,  list(statistics = list(MSD = rnorm(20))))
names(lst1)[2] <- "Hello"

这确实是行不通的.但是,它不适用于声称有效的解决方案.

It is true that it wouldn't work. However, it wouldn't work with the solution claimed to be work as well.

这篇关于列表的子集的子集的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-15 00:32