R:如果向量构成列表的一部分,如何从向量中获取元素?

时间:2018-07-10 13:56:20

标签: r

我有两个列表:

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"))

我还有两种形式的索引:

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

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

MyNIndices反映MyList1中每个向量的哪个元素上出现“ N”?

现在,我希望能够索引到myList2上的相同索引,以便可以获得与N对应的值。所以,我想作为输出

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

OR

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

我该怎么做?

2 个答案:

答案 0 :(得分:2)

在tidyverse中,您可以

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

或者,如果您想返回数字矢量

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

答案 1 :(得分:1)

您可以尝试

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