[Solved] How to convert string rule to an expression which has a range in R [closed]


I’d do it in several steps:

  1. Split on logical operators into separate inequalities.
  2. Change double inequalities like -3>x1>=-1.45 into two inequalities.
  3. Change “=” to “==”, and put it all together.

For example:

a1 <- strsplit(a, "&", fixed = TRUE)[[1]]
a1a <- gsub(" ", "", a1) # get rid of spaces
a2 <- gsub("([-0-9.]+[<>=]+)([[:alpha:]]+[[:alnum:]]*)([<>=]+.+)",
           "\\1\\2 & \\2\\3", a1a)
a3 <- paste(gsub("[^<>]={1}", "==", a2), collapse = " & ")

which gives a3 equal to

[1] "-3>x1 & x1>=-1.45 & -3<=x2 & x2<3 & x==7"

This won’t work if you have other logical operations besides &, or if your variables have non-alphanumeric characters like dots or underscores. It will also fail on inequalities like x1 <= x2 <= x3. I’ll leave you to handle those cases if they come up.

3

solved How to convert string rule to an expression which has a range in R [closed]