[R] if, apply, ifelse

Jim Lemon jim at bitwrit.com.au
Thu Nov 28 10:10:59 CET 2013


On 11/28/2013 04:33 AM, Andrea Lamont wrote:
> Hello:
>
> This seems like an obvious question, but I am having trouble answering it.
> I am new to R, so I apologize if its too simple to be posting. I have
> searched for solutions to no avail.
>
> I have data that I am trying to set up for further analysis ("training
> data"). What I need is 12 groups based on patterns of 4 variables. The
> complication comes in when missing data is present. Let  me describe with
> an example - focusing on just 3 of the 12 groups:
>...
> Any ideas on how to approach this efficiently?
>
Hi Andrea,
I would first convert the matrix "a" to a data frame:

a1<-as.data.frame(a)

Then I would start adding columns:

# group 1 is a 1 (logical TRUE) in col1 and at least one other 1
# here NAs are converted to zeros
a1$group1<-a1$col1 & (ifelse(is.na(a1$col2),0,a1$col2) |
  ifelse(is.na(a1$col3),0,a1$col3) |
  ifelse(is.na(a1$col4),0,a1$col4))
# group 2 is a 1 in col1 and no other 1s
# here NAs are converted to 1s
a1$group2<-a1$col1 & !(ifelse(is.na(a1$col2),1,a1$col2) |
  ifelse(is.na(a1$col3),1,a1$col3) |
  ifelse(is.na(a1$col4),1,a1$col4))
# here NAs are converted to 1s
a1$group3<-!ifelse(is.na(a1$col1),1,a1$col1)

and so on. It is clunky, but then you've got a clunky problem.

Jim



More information about the R-help mailing list