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

Dan Bolser dmb at mrc-dunn.cam.ac.uk
Thu Sep 16 14:55:35 CEST 2004


Minter!

Is there an R cookbook? which lists this kind of common problem and common
solution?


On Thu, 16 Sep 2004, Dimitris Rizopoulos wrote:

>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.
>
>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: "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
>their
>> 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
>bigest
>> 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
>way?
>> (involves some hacky sql)
>>
>> Considering I am interested in the range of the ratio between V1 and
>V2,
>> 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!
>http://www.R-project.org/posting-guide.html
>>
>




More information about the R-help mailing list