Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
803 views
Welcome To Ask or Share your Answers For Others

1 Answer

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...