Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R - Detecting expressions

Tags:

r

What type of object is passed to myFunc as x? It doesn't seem to be an expression, nor a function and str just evaluates it. I understand that I can use force() to evaluate. I'm wondering if there's some way to gather more information about x without evaluating it.

myFunc = function( x )
{
    is.expression( x )    
    is.function( x )
    str( x )
}
myFunc( { x = 5; print( x + 1 ) } )
like image 718
SFun28 Avatar asked Dec 28 '11 14:12

SFun28


2 Answers

You can use match.call for extracting the arguments:

myFunc <- function( x ) {
    x <- match.call()$x
    print(class(x))
    print(typeof(x))
    print(mode(x))
    print(storage.mode(x))
    print(is.expression(x))
    print(is.call(x))
    if (is.call(x)) print(x[[1]])
}
myFunc({x = 5; print("a")})
myFunc(expression(x))
x <- factor(1)
myFunc(x)
myFunc(1)

Probably I need to say that { is a function in R, so {...} is no more than call.

Updated: why x is not function while { is function:

f <- function(x) {
    x <- match.call()$x
    print(eval(x[[1]]))
    print(is.function(eval(x[[1]])))
}

f({1})
like image 134
kohske Avatar answered Sep 29 '22 00:09

kohske


I think class would do the trick... See docs.

EDIT: According to the docs,

for {, the result of the last expression evaluated

Which means the class is the class resulting from the evaluation, which is why it not showing up as an "expression". It is being passed after evaluation.

like image 37
Benjamin Avatar answered Sep 29 '22 01:09

Benjamin