6

次の文字列があります。

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

上記の文字列の 100 を別のベクトルの要素に置き換えたいと思います。

replacement <- c(1000,2000,3000)

文字列の最初の 100 は 1000 に、2 番目の 100 は 2000 に、というように置き換えます。結果の文字列は次のようになります。

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

Rでこれを行う効率的な方法はありますか?

ありがとうございました。

ラヴィ

4

6 に答える 6

2

パーティーに遅れていregmatchesますregmatches(...) <- valueが、この種のことをワンライナーできれいに行うことができる割り当て機能があります。

regmatches(string, gregexpr("100",string)) <- list(replacement)
string
# [1] "1000 this is 2000 test 3000 string"

元の を上書きしたくない場合は、次の方法stringで関数を直接呼び出すことができます。

`regmatches<-`(string, gregexpr("100",string), value=list(replacement))
#[1] "1000 this is 2000 test 3000 string"
于 2013-08-08T01:24:52.743 に答える
0

subとの使用はどうですか*apply

tail(sapply(replacement, function(x) {string <<- sub("\\b100\\b",x,string)}), 1)
于 2013-04-18T14:19:41.530 に答える