2014-09-21 112 views
13

我想合并2个载体是这样的:如何合并2个向量交替索引?

a = c(1,2,3) 
b = c(11,12,13) 
merged vector : c(1,11,2,12,3,13) 

我怎么能这样做呢?

+1

一些方法[这里](http://stackoverflow.com/questions/16443260/interleave-lists-in-r) – 2014-09-21 17:42:59

回答

31

这将工作用rbind

c(rbind(a, b)) 

例如:

a = c(1,2,3) 
b = c(11,12,13) 

c(rbind(a,b)) 

#[1] 1 11 2 12 3 13 
+0

这种解决方案不适用于长度不同的向量,解决方案由@RichardScriven更强大这种情况(如果“长度(a)”大于“长度(b)”或“最大长度”)用于索引)。 – Tim 2015-11-02 08:57:14

7

rbind()答案由@jalapic非常出色。这是一个替代方案,它创建一个新的向量,然后为其分配交替的值。

a <- c(1,2,3) 
b <- c(11,12,13) 

x <- vector(class(a), length(c(a, b))) 
x[c(TRUE, FALSE)] <- a 
x[c(FALSE, TRUE)] <- b 
x 
# [1] 1 11 2 12 3 13 

还有一显示append

c(sapply(seq_along(a), function(i) append(a[i], b[i], i))) 
# [1] 1 11 2 12 3 13 
+0

我爱你对这个问题的回答(尽管在附加的例子中,当我有一个向量有2个项目,另一个有3个项目时,我最终得到一个带有NA的最终向量)。我去了第一个选项,但不太明白这几行发生了什么: x [c(TRUE,FALSE)] < - a x [c(FALSE,TRUE)] < - b 你能解释吗? – 2017-01-31 15:38:23

+1

@PatrickWilliams - 'c(TRUE,FALSE)'用于索引时,表示从**第一个**开始取所有其他值。 'c(TRUE,FALSE)'通过矢量的整个长度被回收(所以在这个例子中就像是说“是,否,是,否,是,否)”。另一方面,'c(FALSE TRUE)'以相同的方式采用以**秒**开始的每个其他值。 – 2017-01-31 18:54:50

1

我不得不解决类似的问题,但我的载体分别是不等长的。而且,我不想回收较短的向量,而是追加较长向量的尾部。

而@RichardScriven的解决方案并不适合我(尽管我可能做了错误的事情,并没有尽力排除故障)。

这里是我的解决方案:

#' Riffle-merges two vectors, possibly of different lengths 
#' 
#' Takes two vectors and interleaves the elements. If one vector is longer than 
#' the other, it appends on the tail of the longer vector to the output vector. 
#' @param a First vector 
#' @param b Second vector 
#' @return Interleaved vector as described above. 
#' @author Matt Pettis 
riffle <- function(a, b) { 
    len_a <- length(a) 
    len_b <- length(b) 
    len_comm <- pmin(len_a, len_b) 
    len_tail <- abs(len_a - len_b) 

    if (len_a < 1) stop("First vector has length less than 1") 
    if (len_b < 1) stop("Second vector has length less than 1") 

    riffle_common <- c(rbind(a[1:len_comm], b[1:len_comm])) 

    if (len_tail == 0) return(riffle_common) 

    if (len_a > len_b) { 
    return(c(riffle_common, a[(len_comm + 1):len_a])) 
    } else { 
    return(c(riffle_common, b[(len_comm + 1):len_b])) 
    } 
} 

# Try it out 
riffle(1:7, 11:13) 
    [1] 1 11 2 12 3 13 4 5 6 7 

riffle(1:3, 11:17) 
    [1] 1 11 2 12 3 13 14 15 16 17 

HTH, 马特

2

只是想添加一个简单的解决方案,为当载体是不等长的作品,你想额外的数据追加到尾部。

> a <- 1:3 
> b <- 11:17 
> c(a, b)[order(c(seq_along(a)*2 - 1, seq_along(b)*2))] 
[1] 1 11 2 12 3 13 14 15 16 17 

说明:

  • c(a, b)创建值的ab的载体。
  • seq_along(a)*2 - 1创建第一个奇数的向量length(a)
  • seq_along(b)*2创建第一个length(b)偶数的向量。
  • order(...)将返回两个seq_along向量中的数字的索引,使得x[order(x)]是有序列表。由于第一个seq_along包含的偶数与第二个seq_along有偏差,因此第一个元素将从第一个元素seq_along开始,然后第二个seq_along的第一个元素,然后从第一个seq_along等第二个元素中插入两个矢量索引并在尾部留下额外的数据。
  • 通过索引c(a, b)使用order向量,我们将穿插ab

作为一个说明,由于seq_along返回numeric(0)当输入为NULL此解决方案有效,即使载体中的一个是长度0

+1

只要'c(a,b)[order(c(seq_along(a),seq_along(b)))]'应该这样做我想。不需要奇数/偶数计算。 – thelatemail 2017-07-27 09:17:17