我有以下字符串:
string <- c("100 this is 100 test 100 string")
我想用上面另一个向量的元素替换上面字符串中的100:
replacement <- c(1000,2000,3000)
字符串的前100个应该替换为1000,第二个100替换为2000,依此类推。结果字符串应如下所示:
result <- c("1000 this is 2000 test 3000 string")
在R中有没有一种有效的方法呢?
谢谢。
拉维
答案 0 :(得分:3)
> cs <- strsplit(string," ")[[1]]
> cs[cs == "100"] <- replacement
> cat(cs)
1000 this is 2000 test 3000 string
答案 1 :(得分:2)
不是很优雅,但这应该做..
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"
答案 2 :(得分:2)
另一种方式(需要将replacement
更改为列表):
string <- c("100 this is 100 test 100 string")
replacement <- list(1000, 2000, 3000)
result <- do.call(sprintf, c(gsub('100', '%d', string), replacement))
答案 3 :(得分: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"
答案 4 :(得分:1)
以下是使用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"
第二行在这里是因为strsplit
在结果开头添加一个空字符串,因为100
出现在第一个位置。
答案 5 :(得分:0)
如何使用sub
和*apply
tail(sapply(replacement, function(x) {string <<- sub("\\b100\\b",x,string)}), 1)