[R] loops: pasting indexes in variables names

Gabor Grothendieck ggrothendieck at myway.com
Wed Sep 22 14:31:03 CEST 2004

Umberto Maggiore <umberto_maggiore <at> hotmail.com> writes:

> I cannot figure out how, using R, I can paste indexes or characters to the 
> variable
> names which are used within loops. I will explain this with a simple 
> example:
> Immagine I have a huge series of variables, each one taken two times, say
> x1 x2 y1 y2 z1 z2.....
> Now, immagine that I want to compute a variable from the difference of
> each couple, say dx=x1-x2, dy=y1-y2, dz=z1-z2...
> In Stata, for example,  this wold be straightforward:
> foreach i in x y z   {
> 		gen  d`i'= `i'1-`i'2
> 		}
> With R I tried to use paste( ) but I found that it applies to objects,
> not to variable names.
> best regards,
> Umberto

You can try this:

paste. <- function(...) paste(..., sep = "")
for(i in c("x", "y", "z"))
   assign(paste.("d", i), get(paste.(i, 1) - paste.(i, 2)))

You also might review why you need this since you may prefer
to use vectors, matrices, arrays, lists or data frames for
this sort of processing.  For example, if they were in a data
frame, DF, then you could write:

   DF[,1] - DF[,2]

and perform all the subtractions at once.

More information about the R-help mailing list