Home > OS >  How to make R filter syntax more user friendly?
How to make R filter syntax more user friendly?

Time:01-12

I am currently working on a R shiny project that need to load in dataset and add criteria to filter out observations.

my issue is when user is entering "flag=1 and condition>=2", the following will convert to "flag==1 and condition>==2" to be readable by R, which is not correct and show error definitely. Is there any function/package can make non-R user to type the condition they want?

    .....if (input$criteria_ad == ""){
      dat <- dat0
    }else if(endsWith(file_ad$name, '.sas7bdat')){
      ad <- data.frame(setDT(read_sas(file_ad$datapath)))
      
      rep_str <- c('<='='<=','>='='>=','='='==','and'='&','or'='|')
      
      ad <- filter(ad, eval(parse(text = str_replace_all(input$criteria_ad, rep_str))))
      
      dat <- inner_join(dat0, ad, by ='ID')
    }......

CodePudding user response:

I think you should be using regex word-boundaries.

With word-boundaries:

rep_str <- c('<='='<=','>='='>=','\\b=\\b'='==','and'='&','or'='|')
str_replace_all("flag=1 and condition>=2", rep_str)
# [1] "flag==1 & condition>=2"

You can do this for all instead of just the singular = with

rep_str <- c('<='='<=','>='='>=','='='==','and'='&','or'='|')
names(rep_str) <- paste0("\\b", names(rep_str), "\\b")
rep_str
#  \\b<=\\b  \\b>=\\b   \\b=\\b \\band\\b  \\bor\\b 
#      "<="      ">="      "=="       "&"       "|" 
str_replace_all("flag=1 and condition>=2", rep_str)
# [1] "flag==1 & condition>=2"

FYI, since the first two elements of your rep_str are no-change, we can omit them from the vector.

  • Related