Skip to content
Prev 333790 / 398506 Next

if, apply, ifelse

On 11/28/2013 04:33 AM, Andrea Lamont wrote:
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