Reputation: 3303
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
Upvotes: 6
Views: 1763
Reputation: 93813
Late to the party, but regmatches
has a regmatches(...) <- value
assignment function which allows you to do this sort of thing cleanly in a one liner:
regmatches(string, gregexpr("100",string)) <- list(replacement)
string
# [1] "1000 this is 2000 test 3000 string"
If you don't want to overwrite your original string
, you could call the function directly via:
`regmatches<-`(string, gregexpr("100",string), value=list(replacement))
#[1] "1000 this is 2000 test 3000 string"
Upvotes: 2
Reputation: 7130
how about using sub
and *apply
tail(sapply(replacement, function(x) {string <<- sub("\\b100\\b",x,string)}), 1)
Upvotes: 0
Reputation: 3210
Another way (need change replacement
to a list):
string <- c("100 this is 100 test 100 string")
replacement <- list(1000, 2000, 3000)
result <- do.call(sprintf, c(gsub('100', '%d', string), replacement))
Upvotes: 2
Reputation: 15441
one way:
> cs <- strsplit(string," ")[[1]]
> cs[cs == "100"] <- replacement
> cat(cs)
1000 this is 2000 test 3000 string
Upvotes: 3
Reputation: 49033
Here is a way to do it with strsplit
:
split <- unlist(strsplit(string, "100", fixed=TRUE))
split <- split[nchar(split) > 0]
paste0(replacement, split, collapse="")
# [1] "1000 this is 2000 test 3000 string"
The second line is here because strsplit
add an empty string at the beginning of its results because 100
appears in the first position.
Upvotes: 1
Reputation: 17189
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"
Upvotes: 2