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

Prof Brian Ripley ripley at stats.ox.ac.uk
Thu Sep 16 14:34:46 CEST 2004


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

-- 
Brian D. Ripley,                  ripley at stats.ox.ac.uk
Professor of Applied Statistics,  http://www.stats.ox.ac.uk/~ripley/
University of Oxford,             Tel:  +44 1865 272861 (self)
1 South Parks Road,                     +44 1865 272866 (PA)
Oxford OX1 3TG, UK                Fax:  +44 1865 272595




More information about the R-help mailing list