Skip to content

Problem with mathematical expression and loop

2 messages · Denis Aydin, Duncan Murdoch

#
Hi to all

I use a loop to plot 9 different histograms of 9 different 
transformations of one dataset (x).

I want to label the histograms with the mathematical expression of each 
transformation (e.g. x^3). For that I've prepared a vector with the 
labeling names for "expression".

 > trans.expr <- c("x^3", "x^2", "x", "frac(1,x)", "frac(1,x^2)",
 > "frac(1,x^3)", "sqrt(x)", "log(x)", "frac(1,sqrt(x))")

 > for(i in 1:9){
 >
 > hist(x[i], main=expression(trans.expr[i]))
 >
 > }

But if I want to pass the names to "expression", it always prints 
"trans.expr[i]" instead of the mathematical expressions.

I also tried to use "noquote" to remove the quotes but it didn't work.

Does anyone knows a solution to that problem?

Any help is appreciated.

Denis
#
On 3/31/2009 9:15 AM, Denis Aydin wrote:
Don't use a character vector, use expressions from the beginning:

trans.expr <- expression(x^3, x^2, x, frac(1,x), frac(1,x^2),
                         frac(1,x^3), sqrt(x), log(x), frac(1,sqrt(x)))
for (i in 1:9) hist(x[i], main=trans.expr[i])

If you really need to use strings, then you need parse() to convert them 
to expressions.

Duncan Murdoch