I have these vectors:
texts=c("AANAAA","NNAAAA","AAAAAA", "NAAANN")
letter=c("C","C","G","T","P","D")
I am trying to replace N for each element in texts and replace it with a character from second array letter by position.
Take "AANAAA", the N at third position should be replaced by the third element of letter, i.e. G
My expected output is:
texts=c("AAGAAA","CCAAAA","AAAAAA", "CAAAPD")
I was trying gsub and a for loop
for (i in 1:6) {
for (j in 1:4)
gsub("N",letter[i],texts[j][i])
}
but it didn't work.
CodePudding user response:
You can do that in base R like this. No loop is required. gregexpr extracts a list of positions in texts where matched. We then replace characters at those positions with corresponding characters in letter using regmatches<-.
m <- gregexpr("N", texts, fixed = TRUE)
regmatches(texts, m) <- lapply(m, \(i, x) x[i], letter)
Output
> texts
[1] "AAGAAA" "CCAAAA" "AAAAAA" "CAAAPD"
CodePudding user response:
Using loops, split texts into letters and replace "N" with corresponding letter:
sapply(strsplit(texts, ""), function(i){
ix <- which(i == "N")
i[ ix ] <- letter[ ix ]
paste(i, collapse = "")
})
# [1] "AAGAAA" "CCAAAA" "AAAAAA" "CAAAPD"
CodePudding user response:
A solution based on tidyverse/purrr:
library(tidyverse)
texts=c("AANAAA","NNAAAA","AAAAAA", "NAAANN")
letter=c("C","C","G","T","P","D")
texts %>%
map(~ str_split(.x, "") %>% unlist %>%
map2_chr(letter, ~ if_else(.x == "N", .y, .x))) %>%
map_chr(~ str_c(.x, collapse = ""))
#> [1] "AAGAAA" "CCAAAA" "AAAAAA" "CAAAPD"
