[R] How to vectorize
Gabor Grothendieck
ggrothendieck at gmail.com
Tue Jun 7 04:36:14 CEST 2005
On 6/6/05, PANTERA Laurent <laurent.pantera at irsn.fr> wrote:
> Dear R-List,
>
> I would like to write nicely the names of some isotopes on a plot. The
> code bellow works fine.
>
> plot(1:10,1:10)
> text(c(2,4,8),c(2,4,8),labels=c(expression(italic(phantom(0)^{78}*Ge)),
> expression(italic(phantom(0)^{137}*Cs)),
> expression(italic(phantom(0)^{129*m}*Te))),
> cex=3
> )
>
> But, since I have a lot of isotopes to write on the plot, I would like
> to construct automatically the labels. So I wrote the code below which
> works fine.
>
> listenoms <- list(nom=c("Ge","Cs","Te"),num=c("78","137","129*m"))
> n <- length(listenoms$nom)
> resu <- "c("
> for( i in 1:(n-1))
> {
> resu <- paste(resu,paste("expression(italic(phantom(0)^{",
> listenoms$num[i],"}*",
> listenoms$nom[i],")),",sep=""))
> }
> resu <- paste(resu,paste("expression(italic(phantom(0)^{",
> listenoms$num[n],"}*",
> listenoms$nom[n],")))",sep=""))
> plot(1:10,1:10)
> text(c(2,4,8),c(2,4,8),labels=eval(parse(text=resu)),cex=2)
>
> I assume there is a better way to do that using vectorization.
> May you help me to find it ?
>
Assuming your setup:
x <- c(2,4,8)
nom <- c("Ge","Cs","Te")
num <- c("78","137","129*m")
plot(1:10)
# the ith label can be generated via
lab <- function(i)
as.expression(bquote(italic(phantom(0)^{.(num[i])}*.(nom[i]))))
# giving the following vectorized solution
labs <- lapply(seq(x), lab)
text(x,x,do.call(c,labs))
# although a 'for' loop is arguably simpler
plot(1:10)
for(i in seq(x)) text(x[i], x[i], lab(i))
More information about the R-help
mailing list