Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/extjs/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
R 替换向量的元素_R - Fatal编程技术网

R 替换向量的元素

R 替换向量的元素,r,R,我有以下字符串: string <- c("100 this is 100 test 100 string") string不是很优雅,但这应该可以 string <- c("100 this is 100 test 100 string") temp <- unlist(strsplit(string, split = "\\s+")) replacement <- c(1000, 2000, 3000) temp[temp == "100"] <- repla

我有以下字符串:

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

string不是很优雅,但这应该可以

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"

string这里有一种使用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"
split单向:

> cs <- strsplit(string," ")[[1]]
> cs[cs == "100"] <- replacement
> cat(cs)
1000 this is 2000 test 3000 string
>cs-cs[cs==“100”]cat(cs)
1000这是2000测试3000字符串

使用
sub
*应用如何

tail(sapply(replacement, function(x) {string <<- sub("\\b100\\b",x,string)}), 1)
tail(sapply(替换,函数(x){string另一种方式(需要将
replacement
更改为列表):


string迟到了,但是
regmatches
有一个
regmatches(…)所以要替换的值总是固定的,这些值出现的次数总是已知的,要替换的数字总是与文本交替,替换向量的长度总是与要替换的值出现的次数匹配?我只是在检查“基本假设”关于这个问题。嗨,阿南达,澄清一下……值是固定的……这些值出现的时间随情况而变化……要替换的数字可以是文本,也可以是其他数字……向量长度总是相同的
> cs <- strsplit(string," ")[[1]]
> cs[cs == "100"] <- replacement
> cat(cs)
1000 this is 2000 test 3000 string
tail(sapply(replacement, function(x) {string <<- sub("\\b100\\b",x,string)}), 1)
string <- c("100 this is 100 test 100 string")
replacement <- list(1000, 2000, 3000)
result <- do.call(sprintf, c(gsub('100', '%d', string), replacement))
regmatches(string, gregexpr("100",string)) <- list(replacement)
string
# [1] "1000 this is 2000 test 3000 string"
`regmatches<-`(string, gregexpr("100",string), value=list(replacement))
#[1] "1000 this is 2000 test 3000 string"