vendredi 22 décembre 2017

Nested if-else with regex in R

I'm working with a list of mathematical expressions. I have identified 6 main patterns of expressions. I'm using a regex to filter out each pattern and write similar expressions to one file and if any expressions doesn't match any of the regex, those will be written to a separate file (Log.txt).

s1 = "(5.0 - 50.0)"

s2 = "((5.0 - 50.0) - 15.0)"

s3 = "(15.0 - (5.0 - 50.0))"

s4 = "((43.0 - 85.0) + (18.0 + 84.0))"

s5 = "(100.0 - ((5.0 - 57.0) + 92.0))"

s6 = "(((12.0 + 89.0) - 73.0) - (58.0 - 90.0))"

I've tried using nested if-else and ifelse() both. The code picks up the first pattern and write it to the "ExpressionType1.txt" then it gives an error. When the pattern is not matching the regex it will not go to the else clause. Below code is only for two types of expressions. Is there any other method to use regex with if-else conditions?

expressionList = read.table("expressionList.txt",header = T,sep = "\n")

for(i in 1:length(expressionList[,1])){

  currentExpression = as.character(expressionList[i,1])  

  ifelse(grepl("^\\(-?\\d+\\.\\d+\\s[\\+\\-\\*\\/]\\s-?\\d+\\.\\d+\\)$",currentExpression, perl = T),
         write(currentExpression,file="ExpressionType1.txt",append=TRUE),
    ifelse(grepl("^\\(\\(-?\\d+\\.\\d+\\s[\\+\\-\\*\\/]\\s-?\\d+\\.\\d+\\)\\s[\\+\\-\\*\\/]\\s-?\\d+\\.\\d+\\)$",currentExpression, perl = T),
                write(currentExpression,file="ExpressionType2.txt",append=TRUE), write(currentExpression,file="Log.txt",append=TRUE)
                        ))


}

nested if-else

  ifelse(grepl("^\\(-?\\d+\\.\\d+\\s[\\+\\-\\*\\/]\\s-?\\d+\\.\\d+\\)$",
          currentExpression, perl = T) == TRUE){

    write(currentExpression,file="ExpressionType1.txt",append=TRUE)

  } else if(grepl("^\\(\\(-?\\d+\\.\\d+\\s[\\+\\-\\*\\/]\\s-?\\d+\\.\\d+\\)\\s[\\+\\-\\*\\/]\\s-?\\d+\\.\\d+\\)$",
          currentExpression, perl = T) == TRUE){ 

    write(currentExpression,file="ExpressionType2.txt",append=TRUE)

  } else{
    write(currentExpression,file="Log.txt",append=TRUE)
  }

Error in ans[test & ok] <- rep(yes, length.out = length(ans))[test & ok] : replacement has length zero

In addition: Warning message:

In rep(yes, length.out = length(ans)) :

'x' is NULL so the result will be NULL

Aucun commentaire:

Enregistrer un commentaire