neuron
neuron

Reputation: 2069

How to gsub second character in a row

I am trying to gsub the second character in a row. I feel like I am close but I can't seem to figure it out. I tried reading about it and looking at other examples. I can't seem to figure it out

Here is what I am trying

df3 <- c("ATG")
df4 <- gsub('^.{0,2}', 'A', df3)
df5 <- gsub('^.{0,2}', 'T', df3)
df6 <- gsub('^.{0,2}', 'G', df3)
df7 <- gsub('^.{0,2}', 'C', df3)

This is what I want the output to looks like

AAG
ATG
AGG
ACG

but the output currently looks like this

AG
TG
GG
CG

I feel like I am close but I can't seem to figure it out

Upvotes: 0

Views: 448

Answers (2)

cwthom
cwthom

Reputation: 393

You could try:

gsub("^(.).{1}", "\\1A", df3)

The (.) gets the first character as a group to extract - matches up with the \\1. Then the .{1} gets the next single character.

Upvotes: 1

DSGym
DSGym

Reputation: 2867

Does is have to be gsub?

substr makes in easy to get the second element

substr(df3, start = 2, stop = 2).

substr(df3, start =  2, stop = 2) <- "A"

Assign the desired character.

Upvotes: 2

Related Questions