ag14
ag14

Reputation: 867

R: How to obtain elements from vectors, if the the vectors form part of a list?

I have two lists:

myList1 <- list(c("","VNW","SPEC","N","BW" ), c("","WW","N","SPEC","ADJ"),c( "","WW","N"), c("","WW","N"), c("","ADJ","N","WW"), c( "","ADJ","N"))

myList2 <- list(c( "","125141","44","4945","3"), c("","114146","77","19","3"), c("","4359","695"), c("","1372","623"), c("","209","71","1"), c( "","33","3"))

I also have indices in either of two forms:

MyNIndices <- c(4,3,3,3,3,3)

or

MyNIndices <- list (4,3,3,3,3,3)

MyNIndices reflect which element on each of the vectors in MyList1 does "N" occur at?

Now, I want to be able to index into the same indices on myList2 so that I can get the value corresponding to N. So, I want as output

MyFinalValues <- c(4945, 77, 695, 623, 71, 3)

OR

MyFinalValues <- list(4945, 77, 695, 623, 71, 3)

How can I do that?

Upvotes: 0

Views: 21

Answers (2)

Ma Li
Ma Li

Reputation: 131

You could try

MyFinalValues <- mapply(function(x,i) x[i],x=myList2, i=MyNIndices)
if(is.list(MyNIndices)) MyFinalValues=list(MyFinalValues)

Upvotes: 1

dmi3kno
dmi3kno

Reputation: 3055

In tidyverse you can

library(purrr)
map2(myList2,MyNIndices, `[[`)

or, if you want a numeric vector back

map2_chr(myList2,MyNIndices, `[[`) %>% 
    as.numeric()

Upvotes: 2

Related Questions