nova
nova

Reputation: 21

gsub in r, only for some values

I am quite new in R, so I am sorry if this is too basic. I have a ".txt" file with 586 rows that look like these:

data:

*M1,D1.13,o,o,o,o,o,-,o,o,o,-,
*M2,D1.13,o,ab,o,o,o,-,o,o,o,-,

but I need these:

*M1 D1.13 o,o,o,o,o,-,o,o,o,-,
*M2 D1.13 o,ab,o,o,o,-,o,o,o,-,

so, I used the gsub fuction:

gsub(",", " ", data)

but it changes all the rest of my data. How can I change only the two first "," of all my data.

Thanks in advance!

Upvotes: 1

Views: 149

Answers (2)

Avinash Raj
Avinash Raj

Reputation: 174696

How can I change only the two first "," of all my data.

You may use sub,

sub("^([^,]*),([^,]*),", "\\1 \\2 ", x)

Example:

> x <- c("*M1,D1.13,o,o,o,o,o,-,o,o,o,-,", "*M2,D1.13,o,ab,o,o,o,-,o,o,o,-,")
> sub("^([^,]*),([^,]*),", "\\1 \\2 ", x)
[1] "*M1 D1.13 o,o,o,o,o,-,o,o,o,-,"  "*M2 D1.13 o,ab,o,o,o,-,o,o,o,-,"

Upvotes: 2

vks
vks

Reputation: 67968

gsub("(?<=\\d),", " ", data)

You can simply use lookbehind.See demo.

https://regex101.com/r/uF4oY4/76

Upvotes: 3

Related Questions