Extract more than one element in each vector in a list R

I have the following list, say a:

> a
[[1]]
 [1] "C" "A" "C" "C" "U" "U" "G" "U" "C" "C" "U" "C" "A" "C" "G" "G" "U" "C"

[[2]]
 [1] "G" "U" "A" "G" "C" "A" "C" "U" "A" "A" "A" "G" "U" "G" "C" "U" "U" "A"

And I have other list, of numbers, which correspond to the indexes of positions I would like to extract from a, say b:

> b
[[1]]
 [1]  3  4  6  7  9 10 11 12

[[2]]
 [1]  1  2  3  4  6  7  8 10

I would like to extract each letter which has an index position corresponding to the vector in list b, say, the output would be something like:

> c
[[1]]
[1] "C" "C" "U" "G" "C" "C" "U" "C"

[[2]]
[1] "G" "U" "A" "G" "A" "C" "U" "A"

I know how to extract one element from each vector in a list, say, I want to extract each first element (index 1) from list a, so I would apply the next code:

lapply(a, '[[', 1)

But how could I extract more than one value?, if a put b instead of "1" in the last code, I get an error...

Error in FUN(X[[i]], ...) : 
  attempt to select more than one element in vectorIndex

Should I use a for loop?

Upvotes: 3

Views: 1805

Answers (2)

Tyler Rinker
Tyler Rinker

Reputation: 109844

Here's an approach that converts the data to tabular format:

a <- list(
    c("C", "A", "C", "C", "U", "U", "G", "U", "C", "C", "U", "C", "A", "C", "G", "G", "U", "C"),
    c("G", "U", "A", "G", "C", "A", "C", "U", "A", "A", "A", "G", "U", "G", "C", "U", "U", "A")
)

b <- list(
    c(3, 4, 6, 7, 9, 10, 11, 12),
    c(1, 2, 3, 4, 6, 7, 8, 10)
)


library(dplyr)

key <- data_frame(
    grp = rep(seq_along(a), lengths(a)),
    element = unlist(a)
) %>%
    group_by(grp) %>%
    mutate(loc = seq_len(n()))

lookup <- data_frame(
    grp = rep(seq_along(b), lengths(b)),
    loc = unlist(b)
)

lookup %>%
    left_join(key, by = c("grp", "loc"))


lookup %>%
    left_join(key, by = c("grp", "loc")) %>%
    {split(.$element, .$grp)}

## $`1`
## [1] "C" "C" "U" "G" "C" "C" "U" "C"
## 
## $`2`
## [1] "G" "U" "A" "G" "A" "C" "U" "A"

Upvotes: 1

DatamineR
DatamineR

Reputation: 9618

You can try:

mapply(function(x,y) x[y], a, b)

Upvotes: 4

Related Questions