Mike S
Mike S

Reputation: 306

replace chars only in specific position

How can I tell R to replace string only in given position? The example below does it in any position. Trying to make it work and can't figure out syntax.

z <- c("alpha 1 bravo 0 charlie_ 0 v1 whiskey 0")
z  #  replace only in pos 25,26  substr(z, 25, 26)
sink('output.txt')
gsub(" 0","**",z)   # <@>><  ??
sink()

Upvotes: 0

Views: 720

Answers (1)

G5W
G5W

Reputation: 37641

Just make it skip 24 characters from the beginning and then test. Also, sub may be better than gsub here.

z <- c("alpha 1 bravo 0 charlie_ 0 v1")
sub("^(.{24}) 0", "\\1**", z)
[1] "alpha 1 bravo 0 charlie_** v1"

Updated string

z2 <- c("alpha 1 bravo 0 charlie_ 0 v1 whiskey 0") 
sub("^(.{24}) 0", "\\1**", z2)
[1] "alpha 1 bravo 0 charlie_** v1 whiskey 0"

Just to be clear, this pattern only changes positions 25 and 26. No positions before or after. It does so by skipping exactly 24 characters from the beginning and then testing for the pattern " 0". Putting parentheses around .{24} cause those first 24 characters to be stored in the variable \1 which is what is used in the "sub" part to put those back.

Upvotes: 2

Related Questions