Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R - format string with brackets and add colon into it

Tags:

r

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?

like image 420
juan wang Avatar asked Oct 29 '22 20:10

juan wang


1 Answers

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.
like image 152
Psidom Avatar answered Nov 15 '22 07:11

Psidom