[R] Conditional operation on columns in data frame
Gabor Grothendieck
ggrothendieck at gmail.com
Sat Mar 11 13:46:18 CET 2006
y is of class "matrix" and $ is used for data frames, not matrices.
Use y[,"x1"] or else create a data frame, data.frame(x1, x2, x3).
On 3/11/06, Sander Oom <slist at oomvanlieshout.net> wrote:
> 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.
>
> ______________________________________________
> 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