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

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


On Thu, 16 Sep 2004, Prof Brian Ripley wrote:

>On Thu, 16 Sep 2004, Dan Bolser wrote:
>
>> 
>> 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
>> }
>
>data$ratioV1V2 <- ifelse(V1>V2, V1/V2, V2/V1) # or pmax(V1,V2)/pmin(V1, V2)
>
>and either attach(data) or use inside with(data, ).
>
>> This is a bit of a hack, and is taking forever for some reson (about
>> 40,000 rows in my data.frame).
>
>You appear to be doing a single calculation 40,000 times.  Did you not get 
>a warning there?  (Maybe 40,000 warnings?)

I don't know what happened.. I think R or emacs got stuck and crashed...

Here is my exact code...

# Read data
interface <- read.table("Data/interface_data", header = TRUE,
row.names="ROW")

About 40,000 rows...

# Sort the pairs...
interfaceRatio <- NULL

for(i in 1:length(row.names(interface))){
  interfaceRatio[i] <-
    if(interface[i,]$C1 > interface[i,]$C2)
      interface[i,]$C2 / interface[i,]$C1
    else
      interface[i,]$C1 / interface[i,]$C2
}

This never finishes (in the lifetime of my patience).

Sorry if this is garbeled junk - I am slow to understand the principals of
the R data structures.

Looking up values from a data.frame is most of what I never remember about
R.


Thanks for the ifelse.

Dan.

>
>




More information about the R-help mailing list