【问题标题】:R: How to obtain elements from vectors, if the the vectors form part of a list?R:如果向量构成列表的一部分,如何从向量中获取元素?
【发布时间】:2018-07-10 13:56:19
【问题描述】:

我有两个列表:

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)

或

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

我该怎么做?

【问题讨论】:

    标签: r


    【解决方案1】:

    在 tidyverse 中你可以

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

    或者,如果你想要一个数字向量返回

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

    【讨论】:

      【解决方案2】:

      你可以试试

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-12-22
        相关资源
        最近更新 更多