[R] Using a loop to define new variables

Barry Rowlingson b.rowlingson at lancaster.ac.uk
Fri May 28 14:13:37 CEST 2010


On Fri, May 28, 2010 at 12:52 PM, Andre Easom <AEasom at sportingindex.com> wrote:
> Hi,
>
> I'm a novice R user, much more used to SAS.  My problem is pretty simple - basically, in a data frame, I have variables named
> x1,....,x10 and y1,...,y10; and I would like to create r1 = x1 / y1 etc
>
> Apologies if this is way too rudimentary - but I couldn't find any posts online which solve this exact issue.

 Well, you can also access columns by number, so if you know what
columns your x's and y's are in you can do:

if you know the columns your x's and y's are in you can do it all at once:

3-column example:

 > foo=data.frame(x1=1:10,x2=1:10,x3=1:10,y1=10:1,y2=runif(10),y3=runif(10))

 > foo[,1:3]/foo[,4:6]
           x1        x2        x3
1   0.1000000  2.037364  4.242166
2   0.2222222 38.651953  2.475068
3   0.3750000  9.351609  4.682223
etc

you can then add this to your data frame:

 > foo=cbind(foo,foo[,1:3]/foo[,4:6])
 > foo
   x1 x2 x3 y1         y2        y3         x1        x2        x3
1   1  1  1 10 0.49083037 0.2357286  0.1000000  2.037364  4.242166
2   2  2  2  9 0.05174383 0.8080586  0.2222222 38.651953  2.475068
3   3  3  3  8 0.32080042 0.6407213  0.3750000  9.351609  4.682223
etc

and fix up the names:

 > names(foo)[7:9]=paste("r",1:3,sep="")
 > foo
   x1 x2 x3 y1         y2        y3         r1        r2        r3
1   1  1  1 10 0.49083037 0.2357286  0.1000000  2.037364  4.242166
2   2  2  2  9 0.05174383 0.8080586  0.2222222 38.651953  2.475068
3   3  3  3  8 0.32080042 0.6407213  0.3750000  9.351609  4.682223

Barry



More information about the R-help mailing list