'replace first and second "-" with "_" and ":" respectively using sub in r

I have a string like:

string <- "a-b-c-d"

I would like to replace the first "-" with "_" and the second one with ':'

I am using the following command, however it replaces all "-" with ":"

gsub("\\-", "_", gsub("\\-", ":", string))

Desired output is: "a_b:c-d"

Any idea is so appreciated?



Solution 1:[1]

You are almost on the right track. Will help you out abit. gsub is greedy and thus will replace every instance of the pattern. So you should rather use sub instead.

You should do:

sub("-", ":", sub("-", "_", string))
[1] "a_b:c-d"

Here you first replace - with _. Since we are using sub, only the first instance is replaced. The string becomes a_b-c-d. Now we just have to replace the first occurrence of - again, this time round with a : instead

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 onyambu