JonMinton
JonMinton

Reputation: 1279

How to extract elements in a list in a list while maintaining higher level structure

Apologies in advance if this has been answered but I've not figured out what to search for.

Say you have a nested list object of the following form:

Ob1 <- list(
   A=vector("list", 5),
   B=vector("list", 5)
)
sub <- c(2,4)

Is there any non-messy way to create a new object Ob2 which contains the same nested structure as Ob1 but only those elements of A and B as indexed by sub? Ideally this is something I'd like that could be generalised to something more than two levels deep.

Many thanks, Jon

Upvotes: 0

Views: 176

Answers (1)

majom
majom

Reputation: 8021

Here is one approach:

# Fill the specified list elements with some random values 
# This makes it easier to check that really the right elements have been extracted
Ob1[["A"]][[2]] <- 2
Ob1[["A"]][[4]] <- 4
Ob1[["B"]][[2]] <- 22
Ob1[["B"]][[4]] <- 44

# Extract the specified list elements
new.list <- lapply(Ob1, function(x)x[sub])

# > new.list
# $A
# $A[[1]]
# [1] 2
# 
# $A[[2]]
# [1] 4
# 
# 
# $B
# $B[[1]]
# [1] 22
# 
# $B[[2]]
# [1] 44

Upvotes: 3

Related Questions