unitedsaga
unitedsaga

Reputation: 111

extracting element of a vector based on index given in a list in R

I am looking to extract elements of a character vector based of the index in a list. For eg: I have a vector CV and index that I will like to extract are in a list AL. I can extract them individually (through a loop) but I was wondering if there's a way that I can do it without having to use the loop (perhaps using apply function). I tried using sapply unsuccessfully.

CV = c("a","b","c","d")
AL = list(c(1,2),c(2,3,4),c(2))

CV[AL[[1]]]
[1] "a" "b"

sapply(CC,'[',AL)

Upvotes: 0

Views: 763

Answers (1)

Gregor Thomas
Gregor Thomas

Reputation: 146224

Your problem is that

sapply(CV,'[',AL)

will (attempt to) iterate over each element of CV, but you want to iterate over each element of AL:

sapply(AL, function(z) CV[z])
# [[1]]
# [1] "a" "b"
# 
# [[2]]
# [1] "b" "c" "d"
# 
# [[3]]
# [1] "b"

Upvotes: 2

Related Questions