Suraj
Suraj

Reputation: 36577

R - Detecting expressions

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 ) } )

Upvotes: 6

Views: 1117

Answers (3)

kohske
kohske

Reputation: 66872

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})

Upvotes: 6

Tyler Rinker
Tyler Rinker

Reputation: 109934

Dason just posted a similar response to this on Talkstats.com for determining if an object is a data frame or a list (click here for a link to that post). I just extended it to an expression which I think suits your needs.

j.list <- function(list, by = NULL){
    print("list")
    print(list)
}

j.data.frame <- function(df, ..., by = NULL){
    print("data frame")
    print(df)
}


j.expression <- function(expression, by = NULL){
    print("expression")
    print(expression)
}

j <- function(x, ...){
    UseMethod("j")
}

j(list(test = "this is a list"))
j(data.frame(test = 1:10))
j(expression(1+ 0:9))

Upvotes: 1

Benjamin
Benjamin

Reputation: 11860

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.

Upvotes: 2

Related Questions