[R] what's going on here with substitute() ?

Tony Plate tplate at blackmesacapital.com
Thu Oct 23 18:58:04 CEST 2003


I was trying to create a function with a value computed at creation time, 
using substitute(), but I got results I don't understand:

 > this.is.R
Error: Object "this.is.R" not found
 > substitute(this.is.R <- function() X, 
list(X=!is.null(options("CRAN")[[1]])))
this.is.R <- function() TRUE
 > # the above expression as printed is what I want for the function definition
 > eval(substitute(this.is.R <- function() X, 
list(X=!is.null(options("CRAN")[[1]]))))
 > this.is.R
function() X
 > this.is.R()
[1] TRUE
 > X
Error: Object "X" not found
 > rm(this.is.R)
 > # Try again a slightly different way
 > substitute(this.is.R <- function() X, 
list(X=!is.null(options("CRAN")[[1]])))
this.is.R <- function() TRUE
 > .Last.value
this.is.R <- function() TRUE
 > eval(.Last.value)
 > this.is.R
function() X
 > this.is.R()
[1] TRUE
 > rm(this.is.R)
 >
Why is the body of the function "X" when I substituted a different 
expression for X? Also, given that the body of the function is X, how does 
the function evaluate to TRUE since X is not defined anywhere (except in a 
list that should have been discarded.)

This happens with both R 1.7.1 and R 1.8.0 (under Windows 2000).

(yes, I did discover the function is.R(), but I still want to discover 
what's going here.)

-- Tony Plate

PS.  In S-plus 6.1, things worked as I had expected:

 > substitute(this.is.R <- function() X, 
list(X=!is.null(options("CRAN")[[1]])))
this.is.R <- function()
F
 > eval(substitute(this.is.R <- function() X, 
list(X=!is.null(options("CRAN")[[1]]))))
function()
F
 > this.is.R
function()
F
 > this.is.R()
[1] F
 >




More information about the R-help mailing list