2017-06-16 45 views
-1

我有一个包含多个虚拟变量的data.frame。它们属于不同的类别,比如颜色和形状。所以一个虚拟物可能被称为“红色”,另一个“椭圆形”等。最终,我想要将这些类别相互对照以找到依赖关系。要做到这一点,首先我必须从几个虚拟变量中创建分类变量。这些变量也必须允许一次采取多种表现形式(例如,一个对象可能不仅仅有一种颜色,而是两种或三种)。从多个虚拟变量中创建一个具有多种可能表现形式的分类变量

其次,我想知道,如果有几个虚拟变量在一个虚拟变量相结合的方式,不添加它们,而只是显示为“1”时,有至少一个值≠0

谢谢您的帮助!

+1

欢迎SO。请看[如何制作一个很好的重现示例](https://stackoverflow.com/a/5963610/7306168) – Bea

回答

0

像这样的东西?

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 

如果你希望能够把它们混合起来,就有点乱......

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 

...但所有你需要的信息是df$all_colors

关于第二个问题,有很多方式到那里,但是这可能是工作...

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