CafféSospeso
CafféSospeso

Reputation: 1188

replace text between two white-spaces in R

I have this string:

  \tBangkok\t 1\tAGGGGCCHCCTTTTCTCTTTCTCT\t.

In this string I want replace the text between "\t" and "\t" (i.e. Bangkok) with Hanoi. So the result will be

   \tHanoi\t 1\tAGGGGCCHCCTTTTCTCTTTCTCT\t

Moreover, I want replace the text between "1\t" and "\t" with a text like

   "AFGGGKKKKCTTJJCTCTTTCTCT"

(with the same lenght).

   \tHanoi\t 1\tAFGGGKKKKCTTJJCTCTTTCTCT\t 

I should do the same for several lines so I would like to find a more general command for doing it.

Upvotes: 2

Views: 75

Answers (1)

Avinash Raj
Avinash Raj

Reputation: 174706

You may try this,

> x <- "\tBangkok\t 1\tAGGGGCCHCCTTTTCTCTTTCTCT\t"
> gsub("\\B\\t\\K\\w+(?=\\t)", "HAnoi", x, perl=T)
[1] "\tHAnoi\t 1\tAGGGGCCHCCTTTTCTCTTTCTCT\t"
> y <- gsub("\\B\\t\\K\\w+(?=\\t)", "HAnoi", x, perl=T)
> gsub("(1\\t)\\w+(\\t)", "\\1AFGGGKKKKCTTJJCTCTTTCTCT\\2", y, perl=T)
[1] "\tHAnoi\t 1\tAFGGGKKKKCTTJJCTCTTTCTCT\t"

Upvotes: 1

Related Questions