Replace elements of vector by vector in R

2019-02-26 03:48发布

问题:

I want to replace few elements of vector by whole second vector. Condition is, that replaced elements of first vector are equal to third vector. Here is an example:

 a <- 1:10
 b <- 5:7
 v <- rnorm(2, mean = 1, sd = 5)

my output should be

 c(a[1:4], v, a[8:10])

I have already tried

 replace(a, a == b, v)
 a[a == b] <- v

but with a little success. Can anyone help?

回答1:

The == operator is best used to match vectors of the same length, or when one of the vector is only length 1.

Try this, and notice in neither case do you get the positional match that you desire.

> a == b
 [1] FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE
Warning message:
In a == b : longer object length is not a multiple of shorter object length
> b == a
 [1] FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE
Warning message:
In b == a : longer object length is not a multiple of shorter object length

Instead, use match() - this gives you the index position where there is a match in the values.

> match(b, a)
[1] 5 6 7

Then:

a <- 1:10
b <- 5:7
v <- rnorm(3, mean=1, sd=5)

a[match(b, a)] <- v

The results:

a
 [1]  1.0000000  2.0000000  3.0000000  4.0000000 -4.6843669  0.9014578 -0.7601413  8.0000000
 [9]  9.0000000 10.0000000


回答2:

Here' another option:

a[a %in% b] <- v

Since in the example described in the OP there are three common numbers in the vectors a and b while v <- rnorm(2, mean = 1, sd = 5) contains only 2 numbers, the vector v will be recycled and a warning will be issued.

The warning and recycling can be prevented, e.g., by defining v as

v <- rnorm(sum(a %in% b), mean = 1, sd = 5)


标签: r vector replace