[R] converting strings to expressions

Sundar Dorai-Raj sundar.dorai-raj at pdf.com
Thu Sep 14 21:44:04 CEST 2006



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 at 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



More information about the R-help mailing list