Bonono Bonono - 3 months ago 9
R Question

How to access all lists within lists with a loop

This is a follow-up question from this one where I wanted to create a list within a list and now I want to be able to access the nested list and peform functions in it too.

I have a list of 3 that has a list of two within it:

my_list

structure(list(a = structure(list(a = structure(list(value = c(1L,
4L), class = structure(c(1L, 1L), .Label = c("a", "b", "c"), class = "factor")), .Names = c("value",
"class"), row.names = c(1L, 4L), class = "data.frame"), b = structure(list(
value = c(2, 1), class = structure(c(2L, 2L), .Label = c("a",
"b", "c"), class = "factor")), .Names = c("value", "class"
), row.names = c(2L, 5L), class = "data.frame")), .Names = c("a",
"b")), b = structure(list(a = structure(list(value = c(6, 1),
class = structure(c(1L, 1L), .Label = c("a", "b", "c", "d"
), class = "factor")), .Names = c("value", "class"), row.names = c(1L,
5L), class = "data.frame"), b = structure(list(value = c(5, 1
), class = structure(c(2L, 2L), .Label = c("a", "b", "c", "d"
), class = "factor")), .Names = c("value", "class"), row.names = c(2L,
6L), class = "data.frame")), .Names = c("a", "b")), c = structure(list(
a = structure(list(value = 5:6, class = structure(c(1L, 1L
), .Label = c("a", "b", "c", "d", "e"), class = "factor")), .Names = c("value",
"class"), row.names = 5:6, class = "data.frame"), b = structure(list(
value = c(4, 1), class = structure(c(2L, 2L), .Label = c("a",
"b", "c", "d", "e"), class = "factor")), .Names = c("value",
"class"), row.names = c(4L, 7L), class = "data.frame")), .Names = c("a",
"b"))), .Names = c("a", "b", "c"))

$a
$a$a
value class
1 a
4 a

$a$b
value class
2 b
1 b


$b
$b$a
value class
6 a
1 a

$b$b
value class
5 b
1 b


$c
$c$a
value class
5 a
6 a

$c$b
value class
4 b
1 b


I want to
subset
each nested list with a loop by
value != 1
so that the resulting list looks like this:

my_list
$a
$a$a
value class
4 a

$a$b
value class
2 b



$b
$b$a
value class
6 a


$b$b
value class
5 b



$c
$c$a
value class
5 a
6 a

$c$b
value class
4 b


With the below code, I can only access
list [[1]][[1]]
,
list[[2]][[2]]
and
list[[3]][[3]]
. How do I access the others with a loop and apply the
subset
function?

for (i in 1:length(my_list)) {
my_list[[i]][[i]] <- subset(my_list[[i]][[i]],my_list[[i]][[i]]$value=1)
}

Answer

We can use a nested lapply or with rapply

lapply(my_list, function(x) lapply(x, function(y) subset(y, value!=1)))
#$a
#$a$a
#  value class
#4     4     a

#$a$b
#  value class
#2     2     b


#$b
#$b$a
#  value class
#1     6     a

#$b$b
#  value class
#2     5     b


#$c
#$c$a
#  value class
#5     5     a
#6     6     a

#$c$b
#  value class
#4     4     b
Comments