【问题标题】:Inserting values into a vector at multiple positions在多个位置将值插入向量中
【发布时间】:2021-07-24 23:25:30
【问题描述】:

假设我们有一个类似的向量

x <- 1:6

我想插入向量的值

y <- 7:10  

位置

z <- c(3, 5, 6)

向量x,即创建向量

c(1,2,3,7,4,5,8,6,9,10)

有没有一种优雅而灵活的方式来做到这一点?提前谢谢!

【问题讨论】:

    标签: r vector insert


    【解决方案1】:

    R.utils 包 (https://rdrr.io/cran/R.utils/man/insert.html) 中有 insert() 函数。

    它完全符合您的要求,但行为略有不同。

    注意,使用此函数,z 表示应插入y 的位置。在您的示例中,它指示应在其后插入的索引。换句话说,您需要将索引移动 +1。

    另请注意,您的yz 的长度不同。对于非自定义函数,这显然需要修改。 不确定是否有解决此问题的功能选项,但我下面的解决方案也应该提供灵活性。

    根据你的例子,这解决了问题:

    library('R.utils')
    
    x <- 1:6
    
    y <- 7:10
    
    z <- c(4, 6, 7)
    
    
    c(insert(x, z, values = y[1:length(z)]), y[-(1:length(z))])
    
    

    【讨论】:

      【解决方案2】:

      这是一个可能有帮助的函数:

      insert_vector <- function(input, position, values) {
        #Create result vector
        res <- numeric(length(input) + length(values))
        #Create an index of input vector
        inds1 <- seq_along(input)
        #Get the position where we want the input vector in result vector
        inds2 <- inds1 + cumsum(inds1 %in% (position + 1))
        #Insert input vector
        res[inds2] <- input
        #Insert new vector at remaining positions
        res[setdiff(seq_along(res), inds2)] <- values
        res
      }
      
      insert_vector(x, z, y)
      #[1]  1  2  3  7  4  5  8  6  9 10
      
      insert_vector(c(3, 1, 3, 5), c(1, 3), c(10, 100))
      #[1]   3  10   1   3 100   5
      

      【讨论】:

        【解决方案3】:

        一个有趣的问题。这是一个可能的解决方案:

        x <- 1:6
        y <- 7:10  
        z <- c(3, 5, 6)
        
        # complete z so that the lengths of z and y match
        z <- c(z, rep(z[length(z)], length(y) - length(z)))
        # get index of y values in final results
        idx_y <- z + seq_along(z)
        # make an empty vector and fill y values at positions idx_y;
        # the remaining positions are left for values from x.
        m <- rep(0, length(c(x, y)))
        m[idx_y] <- y
        m[!seq_along(m) %in% idx_y] <- x
        
        identical(m, c(1,2,3,7,4,5,8,6,9,10))
        # [1] TRUE
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2021-09-27
          相关资源
          最近更新 更多