拆分字符串并替换索引

split string and replace indices

我有这样的规则

rule <- "X[,14]<=-0.00479499999999999 & X[,14]<=-0.00490000000000002 & X[,14]>-0.00595499999999993 & X[,14]<=-0.00593499999999991 & X[,96]>0.000395000000000034 & X[,96]<=0.000859999999999972"
  1. 我需要按索引拆分规则

    rule1 <- "X[14]<=-0.0047 & X[14]<=-0.0049 & X[14]>-0.0059 & X[14]<=-0.0059
    规则 2 <- X[96]>0.0003 & X[96]<=0.0008"

  2. 并在本例中将索引替换为从 1 到 2 的新索引

14,96 到 1,2

rule1 <- "X[,1]<=-0.0047 & X[,1]<=-0.0049 &
          X[,1]>-0.0059 & X[,1]<=-0.0059  

rule2 <-  X[,2]>0.0003 & X[,2]<=0.0008"

我们将'rule'拆分为&',然后将parse_number的数字部分以数字为一组提取到split,然后paste list个元素,最后用stringr中的str_replace_all替换索引

library(stringr)
v1 <- strsplit(rule, "\s*\&\s*")[[1]]

v2 <- trimws(sapply(split(v1, readr::parse_number(v1)), function(x)
          sub("\s*\&\s*$", "", paste(x, collapse=" & "))))
str_replace_all(v2, setNames(as.character(seq_along(v2)), names(v2)))

-输出

#[1] "X[,1]<=-0.00479499999999999 & X[,1]<=-0.00490000000000002 & X[,1]>-0.00595499999999993 & X[,1]<=-0.00593499999999991"
#[2] "X[,2]>0.000395000000000034 & X[,2]<=0.000859999999999972"