2015-06-20 62 views
0

我想要一个简单而有效地创建比较比较表的方法来比较人口和人口子集的调查答案。有效的方式来创建比较表的调查在R

以下是样本数据集:

id <- c(11, 12, 13, 14, 15, 16) 
gender <- c("M", "M", "F", "F", "M", "F") 
trade.belief <- c("I love NAFTA", "I hate NAFTA", "I love NAFTA", "I hate NAFTA", "I hate NAFTA", "I love NAFTA") 
favorite.color <-c("My favorite color is green", "My favorite color is green", "My favorite color is blue", "My favorite color is blue", "My favorite color is blue", "My favorite color is green") 
votes.in.elections <- c("Yes", "Yes", "No", "Yes", "Yes", "Yes") 
df <- data.frame(id, gender, trade.belief, votes.in.elections, favorite.color) 
df.green <- df[df$favorite.color == "My favorite color is green",] 
df.blue <- df[df$favorite.color == "My favorite color is blue",] 

大多数在线调查工具将有一个有效的方式来过滤或选择谁喜欢的颜色绿色人比较,并排到普通人群或人谁像蓝色一样,适合所有调查问题。

所以,如果我想看看大多数人如何投票或类似北美自由贸易协定是他们最喜欢的颜色是绿色的,我可以做

table(df[df$favorite.color == "My favorite color is green",]) 

但是,这不利于比较其他子集化的人群,和这也是查看数据的一种非常低效的方式。

  1. 我想办法在表人想象谁喜欢绿色,既普通人群和人民谁喜欢蓝色,在所有调查问题和变量。比例表,不计数。

  2. 理想情况下,我也想用一个条形图将其可视化。我的想法是,人们会想要使用ggplot上的data.wrapper功能。

回答

0

为了得到一个不错的表比较不同喜欢的颜色和不同层次百分比NAFTA的爱,你可以使用prop.table()功能:

prop.table(table(df$favorite.color, df$trade.belief)) 

为直观起见,你可以使用facet_wrap()功能在ggplot:

df$trade.belief <- as.factor(df$trade.belief) 
ggplot(df, aes(x=trade.belief))+geom_bar()+facet_wrap(~favorite.color) 

另外,如果你在同一个情节想让他们,你可以只使用填充审美:

ggplot(df, aes(x=trade.belief, fill=favorite.color)) + geom_bar()+scale_fill_manual(values=c('blue', 'green')) 
+0

无论有多少列,你如何得到每列的性别差异? – tom