[R] string evaluation

Uwe Ligges ligges at statistik.uni-dortmund.de
Wed Jan 26 11:36:02 CET 2005


Alex Sanchez wrote:

> Hello,
> 
> I would like to be able to compose an expression using some of the arguments I give to a function, that is assuming I have a list such as:
> my.list<-list(A=1:3,B=c("Brave", "new", "world"))
> and a function
> printComponent<-function(component){
>     if (component=="A"||component=="B"){
>         my.expression<-paste("my.list",component,sep="$")
>         print(my.expression)}
>     else{cat("Wrong argument, must be A or B")}
> }
> 
> I would like that a call "printComponent("A")" to be equivalent to calling
> 
>>my.list$A

It's much simpler! Use the [[ as in:

printComponent <- function(component){
     my.list[[component]]
}

Uwe Ligges




> [1] 1 2 3
> but I only obtain 
> 
>>printComponent("A")
> 
> [1] "my.list$A"
> 
> I presume I must evaluate it somehow but I really can't find the instruction in the manuals (I would also appreciate to know where should I have looked at)
> 
> Thanks for the help
> 
> ----------------------------------------------------------
> Dr. Alex Sánchez
> Departament d'Estadística U.B.
> Telf: 34 934021590
> Fax: 34 93 4111733
> e-mail : asanchez at ub.edu
> -----------------------------------------------------------
>         
> 	[[alternative HTML version deleted]]
> 
> ______________________________________________
> R-help at stat.math.ethz.ch mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide! http://www.R-project.org/posting-guide.html




More information about the R-help mailing list