Reputation: 285
I have two vectors x
and y
. I would like to get a new vector z
which is a vector. In first iteration , the first element is form vector y
and the rest is the third elemnt until the end of vector x
, and in the second iteration the second element is from vector y
and the rest is from vector x
(the first, fourth, fifth, ... of vector x
), ...
For example, these vectors are as follows:
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
Upvotes: 0
Views: 226
Reputation: 115485
Writing a function that will do th
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)))
}
eg
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
Upvotes: 2
Reputation: 32996
> 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
Upvotes: 0