[R] Problem getting an ifelse statment to work

Liaw, Andy andy_liaw at merck.com
Tue Oct 7 03:52:44 CEST 2003


This is a "long" way; i.e., not necessarily efficient:

> qs2
 [1] 2 1 1 4 4 4 1 1 1 4 2 4 3 1 4 3 3 2 4 3
> qs9
 [1] 4 4 1 3 4 3 1 3 1 4 1 2 3 3 4 4 1 4 2 3
> decision <- function(a, b) {
+     if (a == 1 || b == 1) return(1)
+     if (a == 2 || b == 2) return(2)
+     if (a == 3 || b == 3) return(3)
+     if (a == 4 || b == 4) return(4)
+     NA
+ }
> mapply(decision, qs2, qs9)
 [1] 2 1 1 3 4 3 1 1 1 4 1 2 3 1 4 3 1 2 2 3

Hope this is what you want.

Andy


> -----Original Message-----
> From: Greg Blevins [mailto:gblevins at mn.rr.com] 
> Sent: Monday, October 06, 2003 11:21 PM
> To: R-Help
> Subject: [R] Problem getting an ifelse statment to work
> 
> 
> Hello R experts,
> 
> I trust I have a simple request.  I have a dataframe which 
> among its contents are two variables, qs2 and qs9, which have 
> the following frequencies.
> 
> > table(qs2)
> qs2
>  1  2  3  4 
> 40 22 11 29 
> 
> > table(qs9)
> qs9
>   1   2   3   4 
> 162 172  91 179 
> 
> I simply want to create a new variable which I have called 
> SchCode that would be filled based on the following logic 
> (written in Systat syntax):
> 
> if qs2 = 1 or qs9 = 1 then let SchCode = 1
> if qs2 = 2 or qs9 = 2 then let SchCode = 2 
> if qs2 = 3 or qs9 = 3 then let SchCode = 3 
> if qs2 = 4 or qs9 = 4 then let SchCode = 4
> 
> I have looked through my two Ripley texts, searched the 
> R-help, and have tried various ifelse statements, but I 
> cannot get it right.  Help would be appreciated.
> 
> Thanks,
> Greg Blevins
> The Market Solutions Group
> 	[[alternative HTML version deleted]]
> 
> ______________________________________________
> R-help at stat.math.ethz.ch mailing list 
> https://www.stat.math.ethz.ch/mailman/listinfo> /r-help
>




More information about the R-help mailing list