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?
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.\\1
and \\2
to refer the first and second capture groups, i.e. two (\\d+)
and format them with a colon inserted.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With