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.
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)
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With