简体   繁体   English

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

[英]Replacing values in a vector by another vector

I have two vectors x and y . 我有两个向量xy I would like to get a new vector z which is a vector. 我想得到一个新的矢量z ,它是一个矢量。 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: 在第一次迭代中,第一个元素是形式向量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

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
> 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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM