[R] creating a variable using concatenation
David Winsemius
dwinsemius at comcast.net
Wed Mar 31 04:22:20 CEST 2010
On Mar 30, 2010, at 9:24 PM, zubin wrote:
> A general problem i run into, i know there must be a simple solution.
>
> I like to create a variable by appending a 1 for example, (i need to
> loop later on from 1 to X, thus the reason for this). So i assign
> the
> variable vplot with this value, however it has quotes and when i use
> it
> in a barplot, it throws an error. but the tcenter$X1 does exist,
> its an
> element of a data frame. So if i type directly it works, but i like
> to
> do this programmatically, as i have to generate a bunch of these plots
> and need to loop.
>
> So how do i concatenate to create a variable, then reference that
> variable in a function call?
>
>
> R> x <- data.frame(1,2,3,4,5,6,7,8)
> R> x
> X1 X2 X3 X4 X5 X6 X7 X8
> 1 1 2 3 4 5 6 7 8
> R> x$X1
> [1] 1
>
> R> i=1
> R> toplot <- paste("x$X",i,sep="")
> R> toplot
> [1] "x$X1"
>
Yes, except consider what happens when you offer "x$X1" to the
interpreter?
[1] "x$X1"
The interpreter does not take it any further because that character
object is atomic, at least I hope that is the correct terminology. You
would need to wrap it up in eval(parse(text= "x$X1") or
eval(parse(text=toplot)) to get it processed of as a language object.
> okay lets test:
>
> R> plot(x$X1)
> -it works i see the plot
>
> however this DOES not work
>
> R> plot(toplot)
What about plot(x[1]) or plot(x[[1]]) or plot(x[i]) or plot(x[[i]])?
Those should all work.
>
> Error in plot.window(...) : need finite 'ylim' values
> In addition: Warning messages:
> 1: In xy.coords(x, y, xlabel, ylabel, log) : NAs introduced by
> coercion
> 2: In min(x) : no non-missing arguments to min; returning Inf
> 3: In max(x) : no non-missing arguments to max; returning -Inf
>
>
> Thus, that's my problem, i know it must be simple - the variable is
> equal to x$X1 but it does not work in a function call? i tried many
> functions - always some type of error.
I think we may need to see what you are planning on doing with this
knowledge, to know what sort of knowledge to offer.
David Winsemius, MD
West Hartford, CT
More information about the R-help
mailing list