Skip to content

Parsing

morota edited this page Dec 19, 2012 · 1 revision

Example of substitute()

# ex1: use substitute() to get the name of named arguments
a <- "hoge"
b <- "piyo"
show <- function(x,y){
	    cat("x is", deparse(substitute(x)) , "which is", x, '\n')
	    cat("y is", deparse(substitute(y)) , "which is", y, '\n')
	    cat("x is", substitute(x) , "which is", x, '\n')
	    cat("y is", substitute(y) , "which is", y, '\n')
	    cat("deparse returns:",class(deparse(substitute(x))), "class", '\n')
	    cat("substitute returns:",class(substitute(x)), "class", '\n')
        }

show(a,b)
x is a which is hoge 
y is b which is piyo 
x is a which is hoge 
y is b which is piyo 
deparse returns: character class 
substitute returns: name class 
 
# ex2
substitute(x+y, list(x=1))
1 + y

Example of invisible()

f1 <- function(x) x
f2 <- function(x) invisible(x)
a <- f1(2) 
b <- f2(2)
a
[1] 2
b
[1] 2

f1(2) # prints the result
[1] 2
f2(2) # it does not print

parse()

# parse() turns a string into an expression
x <- "10 + 2"
parse(text=x)
expression(10 + 2)

eval(parse(text=x)) 
[1] 12

# deparse() turns an expression into a character string
z <- expression(10 * 2)
z
expression(10 * 2)

deparse(z)
[1] "expression(10 * 2)"

Clone this wiki locally