R - Expression Detection

What type of object is passed by myFunc as x? This does not seem to be an expression, but a function, and str just evaluates it. I understand that I can use force() to evaluate. I am wondering if there is a 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 ) } ) 
+6
source share
3 answers

You can use match.call to extract 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) 

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

Updated: why x not function , but { - function :

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

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

EDIT: according to docs ,

for {, the result of the last evaluated expression

This means that the class is a class obtained as a result of evaluation, therefore it is not displayed as an “expression”. It passes after the assessment.

+2
source

Dason just posted a similar answer on Talkstats.com to determine if the object is a data frame or list ( click here to go to this post) . I just expanded it to an expression that I think fits 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)) 
+1
source

Source: https://habr.com/ru/post/904604/


All Articles