[R] How to pass a character argument which contains expressions to arg.names in barplot?

Uwe Ligges ligges at statistik.tu-dortmund.de
Fri Jul 24 18:58:00 CEST 2009



jcano wrote:
> Hi all
> 
> Can anybody help me with this? I am trying to include in an automatic way
> the argument in arg.names in a barplot. I generate the labels I want to
> appear below the bars with a for loop, and they contain subscripts, so I
> need to use expression
> 
>   anch<-0.05
>   esp<-4
>   for (i in 1:dim(Ntot)[1])
>     {
>     naux<-Ntot[i,]
>     naux2<-naux[naux>0]
>     nind<-which(naux>0)
>     tit4<-character(0)
>     for (j in 1:length(nind))
>       {
>       tit4<-c(tit4,paste("expression(n[paste[",i,",",nind[j],"])",sep=""))
>       }
>     windows()
>     barplot(naux2,xlab=eval(expression(substitute(n[i],list(i=i)))),
>    
> arg.names=tit4,col="gray",width=c(anch,anch),axes=TRUE,xlim=c(0,anch*(esp+2)*length(nind)),
>     space=esp,ylim=c(0,max(naux2)),main=paste("State
> #",i),yaxp=c(0,M,Mint));lines(c(0,100),c(0,0))
>     }   # end of for
>  
> but I don't get what I expect. R plots literally the contents of tit4 below
> each bar, i.e., (for the last value of i in the outer for loop)
> 
> "expression(n[paste[5,1])" 
> "expression(n[paste[5,2])" 
> "expression(n[paste[5,3])" 
> "expression(n[paste[5,4])"
> 
> Of course, if I write directly
> arg.names=c(expression(n[paste(5,1)]),expression(n[paste(5,2)]),expression(n[paste(5,3)]),expression(n[paste(5,4)]))
> it works, but then I cannot do ii in an automatic way for all the graphics
> coming from the for (i in 1:dim(Ntot)[1]).
> 
> I have also tried to store in another variable tit5 the whole expression as
>> tit5
> [1]
> "c(expression(n[paste[5,1]),expression(n[paste[5,2]),expression(n[paste[5,3]),expression(n[paste[5,4]))"
> but it doesn't work neither
> 
> I wonder if there is some way that barplot "tells" arg.names to "evaluate"
> the contents of tit4 as expressions, not as characters
> 
> I hope I made myself clear enough
> 
> Thanks in advance to any response
> 
> Cheers!!!!
> 
> Javi



Your code is not reproducible at all since you have not provided any 
data (such as Ntot). Anyway, I guess (untested!) what you want is 
(prettified to make the code readable):

anch <- 0.05
esp <- 4
for (i in 1:dim(Ntot)[1]){
   naux <- Ntot[i,]
   nind <- which(naux > 0)
   naux2 <- naux[nind]
   windows()
   barplot(naux2,
     xlab = substitute(n[i], list(i=i)),
     names.arg = as.expression(lapply(nind,
       function(x) substitute(n[list(i,j)], list(i=i, j=x)))),
     col = "gray", width = c(anch, anch), axes = TRUE,
     xlim = c(0, anch*(esp+2)*length(nind)), space = esp,
     ylim = c(0, max(naux2)), main = paste("State#", i),
     yaxp = c(0, M, Mint)
   )
   lines(c(0, 100), c(0, 0))
}



Uwe Ligges




More information about the R-help mailing list