[R] Conditional operation on columns in data frame

Sander Oom
Sat, 11 Mar 2006 12:23:47 -0000

Dear R-users,

I need to do an SQL like, conditional, operation on a data frame using
an ifelse construction. However I can not get it to work.

Example:
> x1 <- rnorm(10)
> x2 <- rnorm(10)
> x3 <- rnorm(10)
> x3 <- NA
> y <- cbind(x1,x2,x3)
> y
               x1          x2 x3
 [1,] -0.56927780 -0.30952274 NA
 [2,]  0.16355087  0.05911772 NA
 [3,] -0.21899354  2.04583752 NA
 [4,]  0.06368076  1.11661608 NA
 [5,] -1.30249878 -0.63354373 NA
 [6,]  0.04842365  1.47591928 NA
 [7,] -0.32364275 -0.62201121 NA
 [8,] -0.70427823 -0.15485223 NA
 [9,] -0.39563916  2.23504977 NA
[10,] -1.24102239 -0.40991140 NA

Now I want to fill a new column with values from either x2 or x3,
depending on the value in x1. I thought of something like this:
y$x4 <- ifelse(y$x1>0,x2,x3)
y$x4 <- apply(y,1, function(x) {ifelse(x$x1>0,x$x2,x$x3) })

But obviously this did not give the right result.

Any suggestions?

Thanks in advance,

Sander.