Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass character argument and evaluate

Tags:

r

I have a logical operator and a numeric value I want to pass as a single element to a statement in a function (I hear hundreds of R users groaning; I never do this but have a situation I feel it's ok to).

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

How can I make the third line work like:

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

I know it's likely eval and parse but never use them so don't really understand how to use them here.

like image 481
Tyler Rinker Avatar asked Nov 12 '12 06:11

Tyler Rinker


2 Answers

Something like

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

An alternative is eval and parse as you suggested

What <- rowSums( DF[,1:6])

 textcall <- sprintf(" What %s", overlap)

 exprcall <- parse(text = textcall)

 eval( exprcall)
like image 186
mnel Avatar answered Oct 04 '22 18:10

mnel


You have to convert the entire expression to a string, then convert the parsed text to an expression. Finally, call eval() on 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)

Confirming It Works:

identical(eval(expr), as.numeric(rowSums(DF[, 1:6]) > 2))
# [1] TRUE
like image 44
Ricardo Saporta Avatar answered Oct 04 '22 18:10

Ricardo Saporta