[R] Conditional operation on columns in data frame

Sander Oom slist at oomvanlieshout.net
Sat Mar 11 13:47:57 CET 2006


Hi Hong Ooi,

Thanks for your reply! I tried this option as well, but the result is
not as I expect:

> y$x4 <- ifelse(y$x1>0,y$x2,y$x3)
> y
$x4
logical(0)
> class(y)
[1] "list"

Any more ideas?

Thanks,

Sander.


Hong Ooi wrote:
> _______________________________________________________________________________________
> 
> Note: This e-mail is subject to the disclaimer contained at the bottom of this message.
> _______________________________________________________________________________________
> 
> 
> x2 and x3 are not separate objects, but columns of y. So you need to specify that.
>  
> y$x4 <- ifelse(y$x1 > 0, y$x2, y$x3)
>  
>  
> 
> ________________________________
> 
> From: r-help-bounces at stat.math.ethz.ch on behalf of Sander Oom
> Sent: Sat 11/03/2006 11:23 PM
> To: r-help at stat.math.ethz.ch
> Subject: [R] Conditional operation on columns in data frame
> 
> 
> 
> 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
> 
> 
> 
> 
> _______________________________________________________________________________________
> 
> The information transmitted in this message and its attach...{{dropped}}




More information about the R-help mailing list