0

我有两个向量xy。我想得到一个新的向量z,它是一个向量。在第一次迭代中,第一个元素是向量形式y,其余是第三个元素,直到向量结束x,在第二次迭代中,第二个元素来自向量y,其余来自向量x(第一个,第四个,第五个,.. . of vector 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
4

2 回答 2

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
于 2012-09-25T05:58:33.323 回答
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
于 2012-09-25T04:55:07.510 回答