Reputation: 109844
I have a list of character strings (vectors) and I have a list of numeric vectors that I want to use to find the words from the first. I have it arranged as a data table below to help you visualize:
words neg2
1 i, do, not, like, when, she, is, mean 2, 8
2 i, think, its, not, bad 1, 4
I want to extract the 2nd and 8th word from the character string for row one and then the 1st and fourth words from the character string for row 2 as shown in the MATCH column below:
words neg2 MATCH
1 i, do, not, like, when, she, is, mean 2, 8 do, mean
2 i, think, its, not, bad 1, 4 i, not
Code to reproduce the 2 lists:
neg2<-list(c(2, 8), c(1, 4))
x$words <-list(c("i", "do", "not", "like", "when", "she", "is", "mean"),
c("i", "think", "its", "not", "bad"))
I know this is easy I'm just not seeing it. I've tried using match(), with lapply() and various other combinations but am coming up short.
I'd appreciate the most efficient way to achieve this.
Upvotes: 1
Views: 253
Reputation: 1652
words <- list(c("i", "do", "not", "like", "when", "she", "is", "mean"),
c("i", "think", "its", "not", "bad"))
neg2<-list(c(2, 8), c(1, 4))
words[[1]][neg2[[1]]]
words[[2]][neg2[[2]]]
Or, for arbitrarily long lists of words and indexes:
words1 <- list()
for(i in 1:length(words)) {
words1[[i]] <- words[[i]][neg2[[i]]]
}
Looks like you just need to understand how to index lists in R. See http://cran.r-project.org/doc/manuals/R-lang.html#Indexing
Upvotes: 0
Reputation: 109844
I just realized mapply is the answer:
SEL<-function(x, y)x[y]
mapply(SEL, x$words, neg2, SIMPLIFY = FALSE)
Upvotes: 3