[R] loops: pasting indexes in variables names

Dimitris Rizopoulos dimitris.rizopoulos at med.kuleuven.ac.be
Wed Sep 22 14:27:19 CEST 2004


Hi Umberto,

look at ?get, ?assign, ?paste and try the following:

x1 <- rnorm(10)
x2 <- rnorm(10)
y1 <- rnorm(10)
y2 <- rnorm(10)
z1 <- rnorm(10)
z2 <- rnorm(10)
######
names. <- c("x", "y", "z")
for(i in names.){
    res1 <- get(paste(i,"1",sep=""))
    res2 <- get(paste(i,"2",sep=""))
    assign(paste("d",i,sep=""), res1-res2)
}
#######
all.equal(dx, x1-x2)
all.equal(dy, y1-y2)
all.equal(dz, z1-z2)


I hope it helps.

Best,
Dimitris

----
Dimitris Rizopoulos
Ph.D. Student
Biostatistical Centre
School of Public Health
Catholic University of Leuven

Address: Kapucijnenvoer 35, Leuven, Belgium
Tel: +32/16/396887
Fax: +32/16/337015
Web: http://www.med.kuleuven.ac.be/biostat/
     http://www.student.kuleuven.ac.be/~m0390867/dimitris.htm


----- Original Message ----- 
From: "Umberto Maggiore" <umberto_maggiore at hotmail.com>
To: <r-help at stat.math.ethz.ch>
Sent: Wednesday, September 22, 2004 2:12 PM
Subject: [R] loops: pasting indexes in variables names


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




More information about the R-help mailing list