[R] loops: pasting indexes in variables names

Peter Wolf s-plus at wiwi.uni-bielefeld.de
Wed Sep 22 14:45:35 CEST 2004


Umberto Maggiore wrote:

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

Try:
x1<-10
x2<-20
y1<-5
y2<-22
z1<-4
z2<-7
for(i in c("x","y","z")){
  eval(parse(text=paste("d",i,"<-",i,"1 - ",i,"2",sep="")))
}
ls(pattern="d")

output-start
Wed Sep 22 14:38:28 2004
[1] "dx" "dy" "dz"
output-end

but why don't  you  store x1,y1,z1  and x2,y2,z2  in a list:

a<-list(x=1:4, y=1:7, z=1:5)
b<-list(x=(1:4)*10, y=1:7, z=(1:5)-20)
d<-sapply(1:3, function(i) a[[i]]-b[[i]] )

@
output-start
Wed Sep 22 14:43:09 2004
[[1]]
[1]  -9 -18 -27 -36
[[2]]
[1] 0 0 0 0 0 0 0
[[3]]
[1] 20 20 20 20 20
output-end

Peter Wolf




More information about the R-help mailing list