[R] Using evaluate-deparse-substitute

Uwe Ligges ligges at statistik.uni-dortmund.de
Thu Feb 20 11:08:03 CET 2003


Adaikalavan Ramasamy wrote:
> Being the lazy soul I am, I wish to write a function to replace saying
> ls(pattern=...) everytime. Here is what I have:
> 
> lsp <- function(x){
>   y <- eval(deparse(substitute(x))) 
>   print(y)                                   # CHECK
> 
>   print( ls(pattern = eval(y))   )                    # TRY 1
>   print( ls(pattern = eval(deparse(substitute(x)))) ) # TRY 2
> }
> 
> Suppose I have 
> rubbish.in = rubbish.out = grub <- 1
> 
> I get the following when I try
> 
> 
>>lsp(rub)
> 
> [1] "rub"
> character(0)
> character(0)
> 
> Can someone explain/help with this? Thank you very much.
> 
> ______________________________________________
> R-help at stat.math.ethz.ch mailing list
> http://www.stat.math.ethz.ch/mailman/listinfo/r-help


You have to think about environments and scoping rules.
You define another function and ls() is invoked in that functions, thus 
it is called in another environment than you obviously expected.
See ?ls, particularly its argument "name", why the following prints the 
things you expect from ls().

lsp <- function(x){
    y <- deparse(substitute(x))
    print(y)
    print(ls(sys.frame(sys.parent()), pattern = y))
  }

Consider to read
  Venables and Ripley (2000): S Programming, Springer.

Uwe Ligges




More information about the R-help mailing list