# [R] Combining all possible values of variables into a new...

Mon Oct 20 16:10:26 CEST 2008

```I'm trying to create a new column in my data.frame where subjects are categorized depending on values on four other columns. In any other case I would just nest a few ifelse statements, however, in this case i have 4*6*2*3=144 combinations and i get weird 'context overflow' errors. So I wonder if there is a more efficient way of doing this.

For illustrational purposes, let's say i have:

x<-c(1,0,0,1,0,0,1,0,0,1)
y<-c(1,3,2,3,2,1,2,3,2,3)
z<-c(1,2,1,2,1,2,1,2,1,2)
d<-as.data.frame(cbind(x,y,z))

and i do:

d\$myvar <- ifelse(d\$x == 0 & d\$y==1 & d\$z==1 , d\$myvar <- 1,
ifelse(d\$x == 0 & d\$y==1 & d\$z==2 , d\$myvar <- 2,
ifelse(d\$x == 0 & d\$y==2 & d\$z==1 , d\$myvar <- 3,
ifelse(d\$x == 0 & d\$y==2 & d\$z==2 , d\$myvar <- 4,
ifelse(d\$x == 0 & d\$y==3 & d\$z==1 , d\$myvar <- 5,
ifelse(d\$x == 0 & d\$y==3 & d\$z==2 , d\$myvar <- 6,
ifelse(d\$x == 1 & d\$y==1 & d\$z==1 , d\$myvar <- 7,
ifelse(d\$x == 1 & d\$y==1 & d\$z==2 , d\$myvar <- 8,
ifelse(d\$x == 1 & d\$y==2 & d\$z==1 , d\$myvar <- 9,
ifelse(d\$x == 1 & d\$y==2 & d\$z==2 , d\$myvar <- 10,
ifelse(d\$x == 1 & d\$y==3 & d\$z==1 , d\$myvar <- 11,
ifelse(d\$x == 1 & d\$y==3 & d\$z==2 , d\$myvar <- 12, NA))))))))))))

Suggestions?

```