Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
745 views
in Technique[技术] by (71.8m points)

r - Replace elements of vector by vector

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

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

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.8k users

...