climsaver
climsaver

Reputation: 617

Use vectors of a list as index for vectors of another list

I have two lists, each of them containing the same number of vectors. List1 contains vectors all of the same length, while List2 contains vectors of possibly different lenghths. The idea is, to use the content of the vectors of List2 as indices for the corresponding vectors of List1.

Here is some code for an reproducible example:

# create empty lists
List1 <- list()
List2 <- list()


# fill the lists with vectors
set.seed(50)
for (i in 1:1000) {
  List1[[i]] <- sample(0:500, 360, replace= T)
}

set.seed(100)
for (i in 1:1000) {
  List2[[i]] <- sample(0:200, 50, replace= T)
}

Here an example of what I wish to do with extracting a vector from each list:

vec1 <- List1[[1]]
vec2 <- List2[[1]]

# now use the second vector as index for the first one
vec1[vec2]

The question is now, how to transfer this to the entire lists, so that the output is again a list with the resulting vectors?

Anybody with an idea?

EDIT: This is an edit after some very helpful answers with a new structure of lists, the question remains the same.

Here is the code for an reproducible example:

# create empty lists
List1 <- list()
List2 <- list()


# fill the lists with vectors
set.seed(50)
for (i in 1:1000) {
  List1[[i]] <- sample(0:500, 360, replace= T)
}

set.seed(100)
for (i in 1:1000) {
  List2[[i]] <- sample(0:200, 50, replace= T)
}

# create the first level sublists
sublist1 <- list()
sublist2 <- list()
for (i in 1:8) {
  sublist1[[i]] <- List1
  sublist2[[i]] <- List2
}

# create the super lists
superlist1 <- list(sublist1, sublist1, sublist1, sublist1, sublist1, sublist1, sublist1, sublist1)
superlist2 <- list(sublist2, sublist2, sublist2, sublist2, sublist2, sublist2, sublist2, sublist2)

As you can see, the two superlists have the same structure, they only differ in the lengths of the lists of the lowest levels.

So now the question is, how to use the values of superlist2[[1]][[1]][[1]] as vectors for the corresponding element in superlist1, which is superlist1[[1]][[1]][[1]] and so on?

Upvotes: 4

Views: 218

Answers (3)

akrun
akrun

Reputation: 886948

We could use Map in base R

Map(`[`, List1, List2)

Upvotes: 4

TarJae
TarJae

Reputation: 78917

This is my first loop. so it is a try, please be kind:

# loop
for (i in 1:length(List1)) {
    print(List1[[i]][List2[[i]]])
} 

Upvotes: 3

Martin Gal
Martin Gal

Reputation: 16978

You need an apply-function:

lapply(seq_along(List1), function(n) List1[[n]][List2[[n]]])

returns the expected list.

With tidyverse you could use

library(dplyr)
library(purrr)

List1 %>% 
  map2(.y = List2, ~.x[.y])

to get the same result.

Upvotes: 6

Related Questions