R - format the string using brackets and add a colon to it

I am very new to R. I tried to come up with code in R that could help me convert the string using brackets, like the line below:

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

in this format:

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 then remove the brackets, but I do not understand. Can anyone help?

+4
source share
1 answer

You can use a gsubbacklink 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 the bracket where there are two numbers enclosed in one or more spaces. *here you need to match the optional spaces between brackets and numbers.
  • \\1 \\2 , .. (\\d+) .
+1

Source: https://habr.com/ru/post/1655133/


All Articles