-1

I have a data.frame with multiple dummy variables. They belong to different categories, say color and shape. So one dummy might be called "red", another "oval" and so on. Eventually I want to plot those categories against each other to find dependencies. To do that, first of all I have to create categorical variables out of several dummy variables. These variables must also be allowed to take on several manifestations at once (e.g. an object might not just have one color, but two or three).

Secondly, I'd like to know if there's a way to combine several dummy variables in one dummy variable, not adding them, but simply showing "1" when there's at least one value ≠ 0.

Thanks for your help!

  • 1
    Welcome to SO. Please take a look at [How to make a great reproducible example](https://stackoverflow.com/a/5963610/7306168) – Bea Jun 16 '17 at 16:05

1 Answers1

0

Something like this?

red <- c(1,1,0,0,1,1)
green <- c(0,0,1,1,0,1)
blue <- c(0,0,0,1,1,1)
df <- data.frame(red,green,blue)
df
##   red green blue
## 1   1     0    0
## 2   1     0    0
## 3   0     1    0
## 4   0     1    1
## 5   1     0    1
## 6   1     1    1

If you want to be able to combine them, it gets a little messy...

df$redtxt <- ifelse(red==1,"Red","")
df$greentxt <- ifelse(green==1,"Green","")
df$bluetxt <- ifelse(blue==1,"Blue","")
df$all_colors <- with(df, paste0(redtxt,greentxt,bluetxt))

df
##   red green blue redtxt greentxt bluetxt   all_colors
## 1   1     0    0    Red                           Red
## 2   1     0    0    Red                           Red
## 3   0     1    0           Green                Green
## 4   0     1    1           Green    Blue    GreenBlue
## 5   1     0    1    Red             Blue      RedBlue
## 6   1     1    1    Red    Green    Blue RedGreenBlue

...but all the info you need is in df$all_colors.

For your second question, there are many ways to get there, but this could work...

buncha_dummies <- data.frame(x1=c(0,0,0,1,1),x2=c(0,1,0,1,0),x3=c(0,0,0,0,1))
buncha_dummies$ANY_1 <- with(buncha_dummies, 1*(x1==1 | x2==1 | x3==1))
buncha_dummies
##   x1 x2 x3 ANY_1
## 1  0  0  0     0
## 2  0  1  0     1
## 3  0  0  0     0
## 4  1  1  0     1
## 5  1  0  1     1
Matt Tyers
  • 2,125
  • 1
  • 14
  • 23