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
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.
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.
one way:
> cs <- strsplit(string," ")[[1]]
> cs[cs == "100"] <- replacement
> cat(cs)
1000 this is 2000 test 3000 string
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"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With