Split String in R for several signs

Viewed 36

How can I split a string like

x = "0.989(0.975)&0.964(0.937)&0.877(0.771)&&0.962(0.903)&0.971(0.867)&0.932(0.828)&&0.984(0.892)&0.937(0.869)&0.910(0.722)&&0.970(0.867)&0.942(0.811)&0.875(0.747)"

to get all numbers is a numeric vector like

y = c(0.989, 0.975, 0.964, 0.937, 0.877)

and so on.

I want to eliminate the parentheses, the "&" and "&&".

2 Answers

Use gsub with scan i.e. gsub to replace all the characters other than the . and digits with a single delimiter , and then with scan read it at once

out <- scan(text = gsub("[^.0-9]+", ",", x), what = numeric(), 
    sep=",", quiet = TRUE)

str(out)
#num [1:25] 0.989 0.975 0.964 0.937 0.877 0.771 0.962 0.903 0.971 0.867 ...

Another option using regmatches + as.numeric

as.numeric(regmatches(x, gregexpr("\\d+\\.\\d+", x))[[1]])

gives

 [1] 0.989 0.975 0.964 0.937 0.877 0.771 0.962 0.903 0.971 0.867 0.932 0.828
[13] 0.984 0.892 0.937 0.869 0.910 0.722 0.970 0.867 0.942 0.811 0.875 0.747
Related