2015-09-04 50 views
2

substring() <- valuesubstr() <- 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" 

回答

2

完成之後,也許我的方式是比較複雜的,但在這裏我們去:

f <- function(x, strings, replaces){ 
    e <- new.env() 
    e$x <- x 
    if(length(strings)!=length(replaces)) print("Strings should have the same number of elements as replaces") else { 

    foo2 <- function(i){ 
    e$x <- gsub(strings[i], replaces[i], e$x) 
} 
lapply(1:length(strings), foo2) 

} 
return(e$x) 
} 


string <- "a string" 
strings <- c("a", "r", "ng") 
replaces <- c("that", "", "nks") 


f(string, strings, replaces) 


[1] "that stinks" 
+0

我最終想要提供一個字符串,一個指示向量的向量,指示我想要替換哪些字符,以及替換字符作爲向量。你的例子的工作原理是因爲要替換的模式包含獨特的元素,但我不確定它能否解決我的問題(我想通過替換通常相同但位於字符串中不同位置的鹼基來突變基因)。 – jeanlain

3

我不真正明白你在找什麼,因爲你甚至可以說你的榜樣並不代表你實際在做什麼。

可能通過使用()也稱爲捕獲組:

gsub("(.*)(this)(.*)", '\\1him\\3', 'get this off my desk') 
[1] "get him off my desk" 

括號創建組。然後R可以使用雙反斜槓符號引用捕獲組號:\\1\\2等。這裏我有3個基團

  1. get
  2. this
  3. off my desk

在我的代碼,我用him代替this(第2組)。

+0

我編輯了我的問題,以更好地解釋我在找什麼。 – jeanlain

+0

這不會做我在我編輯的問題中描述的。我需要替換特定位置的字符,而不管字符本身。我需要替換位置x上的字符,而不管它是「A」,「C」還是「G」或其他。 – jeanlain