Re: [R] converting strings to expressions

From: Sundar Dorai-Raj <sundar.dorai-raj_at_pdf.com>
Date: Thu 14 Sep 2006 - 19:44:04 GMT

Deepayan Sarkar said the following on 9/14/2006 2:31 PM:
> Hi,
>
> consider this:
>
> --------------
>
> estr <- c("2^4", "alpha[1]")
> eexp <- expression(2^4, alpha[1])
>
>
> ## Is it possible to get 'eexp' starting from 'estr'? The closest I could
> ## get was:
>
> do.call(expression, lapply(estr, as.name))
>
> ## but it is not quite the same; e.g. the following behave differently:
>
> library(lattice)
>
> xyplot(1:10 ~ 1:10,
> scales = list(x = list(at = c(3, 6), labels = eexp)))
>
> xyplot(1:10 ~ 1:10,
> scales = list(x = list(at = c(3, 6),
> labels = do.call(expression,
> lapply(estr, as.name)))))
>
> ---------------
>
> This happens in both 2.3.1 and pre-2.4.0.
>
> Deepayan
>
>

>> sessionInfo()

> Version 2.3.1 Patched (2006-08-27 r39012)
> x86_64-unknown-linux-gnu
>
> attached base packages:
> [1] "methods" "stats" "graphics" "grDevices" "utils" "datasets"
> [7] "base"
>
> other attached packages:
> lattice
> "0.13-10"
>
>> sessionInfo()

> R version 2.4.0 Under development (unstable) (2006-08-30 r39022)
> x86_64-unknown-linux-gnu
>
> locale:
> C
>
> attached base packages:
> [1] "methods" "stats" "graphics" "grDevices" "utils" "datasets"
> [7] "base"
>
> other attached packages:
> lattice
> "0.14-3"
>
> ______________________________________________
> R-help@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
> and provide commented, minimal, self-contained, reproducible code.

Hi, Deepayan,

Will this work for you?

estr <- c("2^4", "alpha[1]")
eexp <- expression(2^4, alpha[1])

library(lattice)

xyplot(1:10 ~ 1:10,

        scales = list(x = list(at = c(3, 6), labels = eexp)))

estr.2 <- sprintf("expression(%s)", paste(estr, collapse = ",")) eexp.2 <- eval(parse(text = estr.2))
xyplot(1:10 ~ 1:10,

        scales = list(x = list(at = c(3, 6), labels = eexp.2)))

Works in both R-2.3.1 and R-2.4.0dev.

Typically, I don't like using eval(parse(text=...)), but I've run into this problem before I could not see another way. Perhaps Gabor will enlighten us with something slicker.

HTH, --sundar



R-help@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 and provide commented, minimal, self-contained, reproducible code. Received on Fri Sep 15 05:47:57 2006

Archive maintained by Robert King, hosted by the discipline of statistics at the University of Newcastle, Australia.
Archive generated by hypermail 2.1.8, at Thu 14 Sep 2006 - 20:16:55 GMT.

Mailing list information is available at https://stat.ethz.ch/mailman/listinfo/r-help. Please read the posting guide before posting to the list.