set.seed(123) > dat <- data.frame(v1 = sample(c(T,F), 10, TRUE), + v2 = sample(c(T,F), 10, TRUE), + v3 = sample(c(T,F), 10, TRUE), + v4 = sample(c(T,F), 10, TRUE) + ) > dat
The first strategy uses a different combination of patterns for indexing into a character vector with a default value of 1 for the Other index:
> dat$bcateg <- c("Other", "v2 only", "v1 and v3", "All")[1+ + with(dat, 1*(v2 & !v1 &!v3 &!v4)) + +with(dat, 2*(v1&v3))+ + with(dat, v1&v2&v3&v4)] > dat v1 v2 v3 v4 bcateg 1 TRUE FALSE FALSE FALSE Other 2 FALSE TRUE FALSE FALSE v2 only 3 TRUE FALSE FALSE FALSE Other 4 FALSE FALSE FALSE FALSE Other 5 FALSE TRUE FALSE TRUE Other 6 TRUE FALSE FALSE TRUE Other 7 FALSE TRUE FALSE FALSE v2 only 8 FALSE TRUE FALSE TRUE Other 9 FALSE TRUE TRUE TRUE Other 10 TRUE FALSE TRUE TRUE v1 and v3
The second strategy combines TRUE column names using the delimiter ",":
> dat$bcateg2 <-paste( c("","v1")[dat[["v1"]]+1 ], c("","v2")[dat[["v2"]]+1 ], c("","v3")[dat[["v3"]]+1 ], c("","v4")[dat[["v4"]]+1 ], sep = ",") > dat v1 v2 v3 v4 bcateg bcateg2 1 TRUE FALSE FALSE FALSE Other v1,,, 2 FALSE TRUE FALSE FALSE v2 only ,v2,, 3 TRUE FALSE FALSE FALSE Other v1,,, 4 FALSE FALSE FALSE FALSE Other ,,, 5 FALSE TRUE FALSE TRUE Other ,v2,,v4 6 TRUE FALSE FALSE TRUE Other v1,,,v4 7 FALSE TRUE FALSE FALSE v2 only ,v2,, 8 FALSE TRUE FALSE TRUE Other ,v2,,v4 9 FALSE TRUE TRUE TRUE Other ,v2,v3,v4 10 TRUE FALSE TRUE TRUE v1 and v3 v1,,v3,v4