Home > OS >  Split comma separated string with commas as decimal delimiter into numbers
Split comma separated string with commas as decimal delimiter into numbers

Time:12-17

I am writing to ask a simple question, but I have not been able to solve it. I want to separate a string in R, in which there are comma delimited decimal numbers, which also are comma separated. The only regularity that exists is that any number has only two decimal places, but sometimes the numbers are in parentheses.

input:

0,60,(0,50),0,71,1,28,1,77,1,60,1,87

desired result:

0.60, (0.50), 0.71, 1.28, 1.77, 1.60, 1.87

CodePudding user response:

Here is a way:

input <- '0,60,(0,50),0,71,1,28,1,77,1,60,1,87'

spl <- strsplit(input, ',')[[1]]
even <- !(seq_along(spl) %% 2)
paste0(spl[!even], '.', spl[even])
# [1] "0.60"   "(0.50)" "0.71"   "1.28"   "1.77"   "1.60"   "1.87"  

Splits input in ',' and reconcatenates subsequent odd and even parts with '.'.

CodePudding user response:

You can try look-aheads.

el((strsplit(x, ',(?=\\()|,(?=\\d{1},)', perl=TRUE)))
# [1] "0,60"   "(0,50)" "0,71"   "1,28"   "1,77"   "1,60"   "1,87"  

Data:

x <- '0,60,(0,50),0,71,1,28,1,77,1,60,1,87'
  • Related