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

Andy Bunn abunn at whrc.org
Thu Sep 16 14:51:17 CEST 2004


ifelse accomplishes this pretty easily (at least I think it does what you
want)

Look at ?apply too.

HTH, Andy


## Try this
foo.dat <- data.frame(Var1 = rnorm(40000, 1, 1),
                      Var2 = (rnorm(40000, 1, 1) * 0.25))
plot(density(foo.dat$Var1 / foo.dat$Var2))

RatioOne <- ifelse(foo.dat$Var1 > foo.dat$Var2,
                   foo.dat$Var1 / foo.dat$Var2,
                   foo.dat$Var2 / foo.dat$Var1)

RatioTwo <- numeric()
for (i in 1:nrow(foo.dat)) {
  RatioTwo[i] <- if(foo.dat$Var1[i] > foo.dat$Var2[i]) foo.dat$Var1[i] /
foo.dat$Var2[i]
                 else foo.dat$Var2[i] / foo.dat$Var1[i]
}
cor(RatioOne, RatioTwo)




More information about the R-help mailing list