用另一个向量替换向量中的值

时间:2012-09-25 04:31:31

标签: r vector

我有两个向量xy。我想得到一个新的向量z,这是一个向量。在第一次迭代中,第一个元素是形式向量y,其余的是第三个元素,直到向量x结束,而在第二个迭代中,第二个元素来自向量y,其余的来自向量x(向量x的第一,第四,第五,......),... 例如,这些载体如下:

  x = c(1, 3, 5, 6, 8)
  y = c(2, 4, 56, 77)

 > z
      [,1] [,2] [,3] [,4]
[1,]    2    5    6    8
[2,]    1    4    6    8
[3,]    1    3   56    8
[4,]    1    3    5   77

2 个答案:

答案 0 :(得分:2)

编写将执行的功能

foo <- function(x,y,i){ x[i] <- y; x <- x[-(i+1)];x}
do_foo <- function(x,y){
 if(length(y) > length(x)) {stop('y is longer than x')}
 t(mapply(foo, i = as.list(seq_along(y)), y = as.list(y), MoreArgs =list(x =x)))
}

例如

x <- 10:1
y <- 1:5


do_foo(x,y)
##      [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9]
## [1,]    1    8    7    6    5    4    3    2    1
## [2,]   10    2    7    6    5    4    3    2    1
## [3,]   10    9    3    6    5    4    3    2    1
## [4,]   10    9    8    4    5    4    3    2    1
## [5,]   10    9    8    7    5    4    3    2    1

答案 1 :(得分:0)

> foo <- sapply(y, function(X) c(X, x[-c((which(y == X)+1), (which(y == X)))]))
> foo
     [,1] [,2] [,3] [,4]
[1,]  1.5  2.5  3.5  4.5
[2,]  3.0  1.0  1.0  1.0
[3,]  4.0  4.0  2.0  2.0
[4,]  5.0  5.0  5.0  3.0


> foo[, 1]
[1] 1.5 3.0 4.0 5.0
> foo[, 2]
[1] 2.5 1.0 4.0 5.0
> foo[, 3]
[1] 3.5 1.0 2.0 5.0
> 
If you need them sorted:

> foo[order(foo[, 2]) ,2]
[1] 1.0 2.5 4.0 5.0

> foo[order(foo[, 3]) ,3]
[1] 1.0 2.0 3.5 5.0