substring() <- value
或substr() <- value
只能替換每個單詞的單個字符範圍。我想知道如果我想要替換字符串中的幾個不相交的字符,最好的解決方案是什麼。我目前的解決方案是這樣的。替換R中的字符串的單獨部分
string <- "a string"
splitted <- strsplit(string,"",T)[[1]]
splitted[c(1,5,8)] <- c("that", "", "ks")
paste(splitted, collapse="")
[1] "that stinks"
當然,這是一個隨機的例子。我實際上想要在幾百個不同的位置替換基因中的核苷酸。請注意,單個字符(基數)將始終由單個字符替換,與此處的示例相反。
我也可以在一個循環中調用substr() <- value
先後(我不認爲我能避免循環,如果我用substr()
因爲我需要幾次處理之前的結果),但是這可能會慢一些。
感謝您的建議。
編輯:我的例子是誤導性的,這裏是我的測試功能
replaceCharsInString <-function(string, positions, replacement) {
splitted <- strsplit(string,"",T)[[1]]
splitted[positions] <- replacement #'replacement' is a character vector
paste(splitted,collapse="")
}
> replaceCharsInString("ACCTTTAAGAGATTTAGGGAGA", c(2,5,7), c("G","C","C"))
[1] "AGCTCTCAGAGATTTAGGGAGA"
我最終想要提供一個字符串,一個指示向量的向量,指示我想要替換哪些字符,以及替換字符作爲向量。你的例子的工作原理是因爲要替換的模式包含獨特的元素,但我不確定它能否解決我的問題(我想通過替換通常相同但位於字符串中不同位置的鹼基來突變基因)。 – jeanlain