[R] using get and paste in a loop to return objects for object names listed a strings

Paul Hiemstra p.hiemstra at geo.uu.nl
Thu Apr 29 11:05:09 CEST 2010


Nevil Amos wrote:
> I am trying to create a heap of boxplots, by looping though a series 
> of factors and variables in a large data.frame suing paste to 
> constrcut the facto and response names from the colnames
> I thought I could do this using get()
> however it is not working what am I doing wrong?
You don't give a reproducible example, this makes it hard to answer your 
question.

But not really in response to your question, take a look at histogram 
from the lattice package or geom_boxplot from the ggplot2 package. These 
functions can do all the work for you of drawing boxplots for a series 
of factors and variables in a large data.frame. This saves you a lot of 
time.

cheers,
Paul
>
> thanks
>
> Nevil Amos
>
>> sp.codes=levels(data.all$CODE_LETTERS)
>>
>> for(spp in sp.codes) {
>>
>>
>> data.sp=subset(data.all,CODE_LETTERS==spp)
>>
>> responses = colnames(data.all)[c(20,28,29,19)]
>>  #if (spp=="BT") responses = colnames(data.all)[c(19,20,26:29)]
>> groups=colnames   (data.all)[c(9,10,13,16,30)]
>>
>> data.sp=subset(data.all,CODE_LETTERS==spp)
>> for (response in responses){
>> for (group in groups){
>> r<-get(paste("data.sp$",response,sep=""))
>> g<-get(paste("data.sp$",group, sep=""))
>> print (r)
>> print(g)
>>
>> boxplot(r ~g)
>> }}}
> Error in get(paste("data.sp$", response, sep = "")) :
>   object 'data.sp$Hb' not found
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide 
> http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.


-- 
Drs. Paul Hiemstra
Department of Physical Geography
Faculty of Geosciences
University of Utrecht
Heidelberglaan 2
P.O. Box 80.115
3508 TC Utrecht
Phone:  +3130 274 3113 Mon-Tue
Phone:  +3130 253 5773 Wed-Fri
http://intamap.geo.uu.nl/~paul
http://nl.linkedin.com/pub/paul-hiemstra/20/30b/770



More information about the R-help mailing list