Skip to content

use expression() in a loop

9 messages · Nanye Long, Sundar Dorai-Raj, Marc Schwartz +6 more

#
Hi all,

I want to do plot() in a loop to make 10 graphs, so I have some code like

for (i in 1:10) {
   plot(... ... , xlab = expression(g[i]) )
}

I expect g_1, g_2, and so on appear on x labels, but it simply prints
g_i for each graph. Does anybody know how to get around this problem?
Thanks.

NL
#
Nanye Long said the following on 8/18/2008 3:00 PM:
Try:

par(mfrow = c(2, 5))
for (i in 1:10) {
   plot(1, 1, xlab = bquote(g[.(i)]))
}

HTH,

--sundar
#
on 08/18/2008 05:00 PM Nanye Long wrote:
Try this:

par(mfrow = c(5, 2))

for (i in 1:10)
  plot(1, xlab = bquote(g[.(i)]))


Note the use of bquote() and the use of .(i), which replaces 'i' with
the value of i in each iteration.

See ?plotmath for some examples and ?bquote

HTH,

Marc Schwartz
#
...or use the more generic substitute() to replace parts of an expression, e.g.

  i <- 3;
  xlab1 <- substitute(g[idx], list=list(idx=i));
  xlab2 <- bquote(g[.(i)]);
  stopifnot(identical(xlab1, xlab2));

/Henrik


On Mon, Aug 18, 2008 at 3:18 PM, Marc Schwartz
<marc_schwartz at comcast.net> wrote:
6 days later
#
Try this:
[1] "1 2\n3 4\n5 6"

        
On Mon, Aug 25, 2008 at 7:36 PM, remko duursma <remkoduursma at hotmail.com> wrote:

  
    
#
One possibility is:
y <- rep(" ",6)
y[6] <- ""
y[c(2,4)] <- "\n"
res <- paste(paste(x,y,sep=""),collapse="")
--- On Tue, 26/8/08, remko duursma <remkoduursma at hotmail.com> wrote:

            
#
Try this:
[1] "1 2\n3 4\n5 6\n"

-Christos Hatzis
#
Try this also:

paste(apply(matrix(x, 2), 2, paste, collapse = ' '), collapse = "\n")
On Mon, Aug 25, 2008 at 8:36 PM, remko duursma <remkoduursma at hotmail.com> wrote: