Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replacing elements of a vector

Tags:

r

I have the following string:

string <- c("100 this is 100 test 100 string")

I would like to replace the 100's in the above string with elements of another vector:

replacement <- c(1000,2000,3000)

The first 100 of string should be replace by 1000, second 100 by 2000 and so on. The resulting string should look as follows:

result <- c("1000 this is 2000 test 3000 string")

Is there an efficient way to do this in R?

Thank you.

Ravi

like image 516
Ravi Avatar asked Apr 18 '13 11:04

Ravi


People also ask

How do you replace an element in a vector?

To replace an element in Java Vector, set() method of java. util. Vector class can be used. The set() method takes two parameters-the indexes of the element which has to be replaced and the new element.

How do you change the elements of a vector in R?

Replace the Elements of a Vector in R Programming – replace() Function. replace() function in R Language is used to replace the values in the specified string vector x with indices given in list by those given in values.


2 Answers

one way:

> cs <- strsplit(string," ")[[1]]
> cs[cs == "100"] <- replacement
> cat(cs)
1000 this is 2000 test 3000 string
like image 57
user1317221_G Avatar answered Sep 22 '22 12:09

user1317221_G


Not very elegant, but this should do..

string <- c("100 this is 100 test 100 string")
temp <- unlist(strsplit(string, split = "\\s+"))
replacement <- c(1000, 2000, 3000)
temp[temp == "100"] <- replacement
result <- paste(temp, collapse = " ")

result
## [1] "1000 this is 2000 test 3000 string"
like image 20
CHP Avatar answered Sep 19 '22 12:09

CHP