Skip character argument and evaluate

I have a logical operator and a numerical value that I want to pass as one element to an operator in a function (I heard hundreds of R users moaning, I never do this, but I have a situation in which I feel normal).

DF <- mtcars overlap = "> 2" as.numeric(rowSums(DF[, 1:6]) overlap) 

How to make the third line work like:

 as.numeric(rowSums(DF[, 1:6]) > 2) 

I know this rather eval and parse , but I never use them, so I don’t understand how to use them here.

+6
source share
3 answers

Sort of

 Olap <- unlist(strsplit( overlap, " ")) Thresh <- as.numeric(Olap[2]) Comp <- match.fun(Olap[1]) Comp(rowSums(DF[,1:6]), Thresh) 

The alternative is eval and parse, as you suggested

 What <- rowSums( DF[,1:6]) textcall <- sprintf(" What %s", overlap) exprcall <- parse(text = textcall) eval( exprcall) 
+7
source

You need to convert the entire expression to a string, and then convert the parsed text to an expression. Finally, call eval () in the expression.

eg:

 overlap <- "> 2" # Convert to string exprAsString <- paste0("as.numeric(rowSums(DF[, 1:6]) ", overlap, ")") # Convert to expression, using parse expr <- as.expression(parse(text=exprAsString)) # Then call eval() eval(expr) 

Confirmation of work:

 identical(eval(expr), as.numeric(rowSums(DF[, 1:6]) > 2)) # [1] TRUE 
+7
source

It seems to me that although @mnel's solution is good, this is a situation that can be solved by creating a dummy function inside your main function and using your overlap as an argument to change the body(dummy_function) , It can be a lot cleaner.

+1
source

All Articles