【问题标题】:Combine two vectors alternately交替组合两个向量
【发布时间】:2018-12-16 12:58:13
【问题描述】:

Alternate, interweave or interlace two vectors 这篇博文中,展示了一种交替组合两个向量的便捷方法:

x <- 1:3 ; y <- 4:6
c(rbind(x, y)) # [1] 1 4 2 5 3 6

但是,这种方法只适用于两个向量长度相同的情况。现在我想找到一种通用的方法来做到这一点。

这是我的想法:

  • fun &lt;- function(x, y, n) {...}
  • xy 是两个相同类型的向量,它们的长度可以不同。
  • n表示交替间隔,。

预期输出:

x <- 1:5 ; y <- c(0, 0, 0)
fun(x, y, n = 1) # 1 0 2 0 3 0 4 5
fun(x, y, n = 2) # 1 2 0 3 4 0 5 0
fun(x, y, n = 5) # 1 2 3 4 5 0 0 0

感谢您的帮助。

【问题讨论】:

  • @IceCreamToucan riffle( ) 函数可以处理我的第一个预期输出。第二个和第三个呢?

标签: r


【解决方案1】:

首先将x 拆分为n 组并将其堆叠成一个长data.frame。同样,将yrbind 这些数据帧堆叠在一起,按ind(组号)对它们进行排序并取values 列。

fun <- function(x, y, n) {
  sx <- stack(split(x, c(gl(length(x), n, length(x)))))
  sy <- stack(as.list(setNames(y, seq_along(y))))
  r <- rbind(sx, sy)
  r[order(r$ind), "values"]
}

x <- 1:5 ; y <- c(0, 0, 0)

fun(x, y, 1)
## [1] 1 0 2 0 3 0 4 5
fun(x, y, 2)
## [1] 1 2 0 3 4 0 5 0
fun(x, y, 5)
## [1] 1 2 3 4 5 0 0 0

【讨论】:

    【解决方案2】:

    另一种可能性:

    fun <- function(x, y, n){
      c(x, y)[order(c(ceiling(seq_along(x) / n), seq_along(y)))]}
    
    fun(x, y, 1)
    # [1] 1 0 2 0 3 0 4 5
    
    fun(x, y, 2)
    # [1] 1 2 0 3 4 0 5 0
    
    fun(x, y, 5)
    # [1] 1 2 3 4 5 0 0 0
    

    【讨论】:

      【解决方案3】:

      使用Reduce 的解决方案:

      n <- 2
      res <- Reduce(function(x,i) append(x,y[i],i),n*(length(y):1), x)
      res[is.na(res)] <- 0
      res
      # [1] 1 2 0 3 4 0 5 0
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2018-01-21
        • 2012-10-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多