juan wang
juan wang

Reputation: 65

R - format string with brackets and add colon into it

I'm very new to R. I've tried to come up with a code in R which can help me to convert a string with brackets like the string below:

( 65   97) ( 80   12) ( 82  832) (108   23) 

into a format like this:

65:97 80:12 82:832 108:23

I think I should find the position of the space between each bracket and replace it with : and delete the brackets afterward, but I don't how. Can someone help?

Upvotes: 5

Views: 531

Answers (1)

akuiper
akuiper

Reputation: 215107

You can use gsub with back reference as follows:

gsub("\\( *(\\d+) +(\\d+) *\\)", "\\1:\\2", "( 65 97) ( 80 12) ( 82 832) (108 23)")

# [1] "65:97 80:12 82:832 108:23"
  • \\( *(\\d+) +(\\d+) *\\) matches a parentheses unit where there are two digits enclosed separated by one or more spaces. * here is to match optional spaces between parenthesis and digits.
  • at the replacement part, you can use back reference \\1 and \\2 to refer the first and second capture groups, i.e. two (\\d+) and format them with a colon inserted.

Upvotes: 2

Related Questions