【问题标题】:Match vectors in sequence按顺序匹配向量
【发布时间】:2018-05-02 07:55:49
【问题描述】:

我有 2 个向量。

x=c("a", "b", "c", "d", "a", "b", "c")
y=structure(c(1, 2, 3, 4, 5, 6, 7, 8), .Names = c("a", "e", "b", 
"c", "d", "a", "b", "c"))

我想按顺序将a 匹配到abb,以便x[2] 匹配y[3] 而不是y[7];而x[5] 匹配y[6] 而不是y[1],以此类推。

lapply(x, function(z) grep(z, names(y), fixed=T))

给出:

[[1]]
[1] 1 6

[[2]]
[1] 3 7

[[3]]
[1] 4 8

[[4]]
[1] 5

[[5]]
[1] 1 6

[[6]]
[1] 3 7

[[7]]
[1] 4 8

匹配所有实例。我如何得到这个序列:

1 3 4 5 6 7 8

那么x 中的元素可以相应地映射到y 中的相应值吗?

【问题讨论】:

    标签: r vector string-matching


    【解决方案1】:

    您实际上是在寻找pmatch

    pmatch(x,names(y))
    [1] 1 3 4 5 6 7 8
    

    【讨论】:

      【解决方案2】:

      你可以根据每个元素出现的次数来改变name属性,然后是y的子集:

      x2 <- paste0(x, ave(x, x, FUN=seq_along))
      #[1] "a1" "b1" "c1" "d1" "a2" "b2" "c2"
      names(y) <- paste0(names(y), ave(names(y), names(y), FUN=seq_along))
      y[x2]
      #a1 b1 c1 d1 a2 b2 c2 
      # 1  3  4  5  6  7  8 
      

      【讨论】:

        【解决方案3】:

        另一个使用Reduce的选项

        Reduce(function(v, k) y[-seq_len(v)][k],
            x=x[-1L],
            init=y[x[1L]], 
            accumulate=TRUE)
        

        【讨论】:

          【解决方案4】:

          嗯,我用for循环做到了

          #Initialise the vector with length same as x.
          answer <- numeric(length(x))
          for (i in seq_along(x)) {
            #match the ith element of x with that of names in y.
            answer[i] <- match(x[i], names(y))
            #Replace the name of the matched element to empty string so next time you 
            #encounter it you get the next index.
            names(y)[i] <- ""
          }
          
          answer
          #[1] 1 3 4 5 6 7 8
          

          【讨论】:

            【解决方案5】:

            另一种可能性:

            l <- lapply(x, grep, x = names(y), fixed = TRUE)
            
            i <- as.integer(ave(x, x, FUN = seq_along))
            
            mapply(`[`, l, i)
            

            给出:

            [1] 1 3 4 5 6 7 8
            

            【讨论】:

              【解决方案6】:

              与 Ronak 类似的解决方案,但它不会保留对 y 的更改

              yFoo<-names(y)
              sapply(x,function(u){res<-match(u,yFoo);yFoo[res]<<-"foo";return(res)})
              

              结果

              #a b c d a b c 
              #1 3 4 5 6 7 8 
              

              【讨论】:

                猜你喜欢
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                • 2016-07-21
                • 1970-01-01
                • 2016-01-03
                • 1970-01-01
                相关资源
                最近更新 更多