在 R 中根据名称删除列表中的嵌套列表。

4

我有一个列表的列表,想要移除所有名称为rubbish的列表(在下面示例数据中称为rubbish);(最好使用tidyverse)。

#Example data
list1a <- c(1, 2, 3)
list2a <- c(4, 5, 6)
rubbish <- c(7, 8, 9)

list1b <- c(1, 2, 3)
rubbish <- c(4, 5, 6)
list3b <- c(7, 8, 9)

listA <- list(list1a, list2a, rubbish)
names(listA) <- c("list1a", "list2a", "rubbish")
listB <- list(list1b, rubbish, list3b)
names(listB) <- c("list1b", "rubbish", "list3b")
listAB <- list(listA, listB)
names(listAB) <- c("listA", "listB")
listAB

我试过:

new_list <- discard(listAB, .p = ~str_detect(.x,"rubbish"))
2个回答

3
您可以使用 map 遍历列表,并且 discard 名称为 "rubbish" 的列表。
library(purrr)
map(listAB, ~discard(.x, names(.x) == 'rubbish'))
#Some other variations
#map(listAB, ~keep(.x, names(.x) != 'rubbish'))
#map(listAB, ~.x[names(.x) != 'rubbish'])

#$listA
#$listA$list1a
#[1] 1 2 3

#$listA$list2a
#[1] 4 5 6


#$listB
#$listB$list1b
#[1] 1 2 3

#$listB$list3b
#[1] 7 8 9

在基础 R 中,您可以使用 lapply 函数:

lapply(listAB, function(x) x[names(x) != 'rubbish'])

3

rrapply()rrapply包中的一个实用工具,可用于操作嵌套列表,这些列表具有任意和不均匀的深度。通过condition参数,您可以设置特殊参数.xname以确定节点的名称。

library(rrapply)

rrapply(listAB, condition = function(x, .xname) .xname != "rubbish", how = "prune")

# $listA
# $listA$list1a
# [1] 1 2 3
# 
# $listA$list2a
# [1] 4 5 6
# 
# 
# $listB
# $listB$list1b
# [1] 1 2 3
# 
# $listB$list3b
# [1] 7 8 9

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接