[R] Conditionally swap two columns of a data.frame?

Dimitris Rizopoulos dimitris.rizopoulos at med.kuleuven.ac.be
Thu Sep 16 14:34:00 CEST 2004

Hi Dan,

do you need something like that,

dat <- data.frame(V1=rnorm(40000, 10), V2=rnorm(40000, 10))
ratioV1V2 <- ifelse(dat$V1>dat$V2, dat$V1/dat$V2, dat$V2/dat$V1)

I hope it helps.


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/

----- Original Message ----- 
From: "Dan Bolser" <dmb at mrc-dunn.cam.ac.uk>
To: <r-help at stat.math.ethz.ch>
Sent: Thursday, September 16, 2004 2:19 PM
Subject: [R] Conditionally swap two columns of a data.frame?

> I am doing this a kinda dumb way, and it is apparetnly taking
> forever.
> I have a data frame with two numeric columns. I want to look at
> correlation, and I am looking at the size ratio between the two.
> i.e.
> plot(density(data$V1/data$V2))
> This kinda gives me a normal curve showing something about the
> distribution of the two values.
> I want to make sure that V1/V2 is always > 1 ...
> for (i in 1:length(row.names(data)) ){
>   ratioV1V2 <- if(V1>V2) V1/V2 else V2/V1
> }
> This is a bit of a hack, and is taking forever for some reson (about
> 40,000 rows in my data.frame).
> I would just like to swap the values in the data frame (to put the
> first for example), then use the above plot to get what I want.
> Should I use the DB backend to the data to make the dump in this
> (involves some hacky sql)
> Considering I am interested in the range of the ratio between V1 and
> should I be looking at doing a different analysis?
> I am so dumb, any help is appreciated,
> Dan.
> ______________________________________________
> R-help at stat.math.ethz.ch mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide!

More information about the R-help mailing list