R separate numbers and characters in a string

I have a string

rule <- "X[,16] <= -0.664 & X[,11] <= -2.1891 & X[,17] >= -0.4138"

I want to split a string into two parts

num_part = c(16 , -0.664 , 11 , -2.1891 , 17 , -0.4138)
char_part = c("X[,]<= & X[,] <= & X[,] >=")

I found a similar question but I couldn’t apply any of the eight examples to my data

>Solution :

We may use

library(stringr)
 scan(text = str_remove_all(rule, "\\[|\\]|\\>=|<=|&|X|,"), what = numeric(), quiet = TRUE)
[1] 16.0000 -0.6640 11.0000 -2.1891 17.0000 -0.4138
str_remove_all(rule, "[0-9.-]+")
[1] "X[,] <=  & X[,] <=  & X[,] >= "

Leave a Reply