2016-10-04 128 views
0

我有一个Qualtrics多选题,我想用它来在R中创建图表。我的数据是组织的,因此您可以为每个问题回答多个答案。例如,参与者1选择了多选答案1(Q1_1)& 3(Q1_3)。我想在一个条形图中折叠所有答案选项,每个多重答案选项(Q1_1:Q1_3)的一个条数除以回答此问题的答复者数(此例中为3)。R选择问卷数据ggplot

df <- structure(list(Participant = 1:3, A = c("a", "a", ""), B = c("", "b", "b"), C = c("c", "c", "c")), .Names = c("Participant", "Q1_1", "Q1_2", "Q1_3"), row.names = c(NA, -3L), class = "data.frame") 

我想使用ggplot2,也许通过Q1_1某种循环:Q1_3?

回答

2

也许这就是你想要的

f <- 
    structure(
    list(
     Participant = 1:3, 
     A = c("a", "a", ""), 
     B = c("", "b", "b"), 
     C = c("c", "c", "c")), 
    .Names = c("Participant", "Q1_1", "Q1_2", "Q1_3"), 
    row.names = c(NA, -3L), 
    class = "data.frame" 
) 


library(tidyr) 
library(dplyr) 
library(ggplot2) 

nparticipant <- nrow(f) 
f %>% 
    ## Reformat the data 
    gather(question, response, starts_with("Q")) %>% 
    filter(response != "") %>% 

    ## calculate the height of the bars 
    group_by(question) %>% 
    summarise(score = length(response)/nparticipant) %>% 

    ## Plot 
    ggplot(aes(x=question, y=score)) + 
    geom_bar(stat = "identity") 

enter image description here

0

以下是使用dplyr包的ddply解决方案。

# I needed to increase number of participants to ensure it works in every case 
df = data.frame(Participant = seq(1:100), 
Q1_1 = sample(c("a", ""), 100, replace = T, prob = c(1/2, 1/2)), 
Q1_2 = sample(c("b", ""), 100, replace = T, prob = c(2/3, 1/3)), 
Q1_3 = sample(c("c", ""), 100, replace = T, prob = c(1/3, 2/3))) 
df$answer = paste0(df$Q1_1, df$Q1_2, df$Q1_3) 

summ = ddply(df, c("answer"), summarize, freq = length(answer)/nrow(df)) 

## Re-ordeing of factor levels summ$answer 
summ$answer <- factor(summ$answer, levels=c("", "a", "b", "c", "ab", "ac", "bc", "abc")) 

# Plot 
ggplot(summ, aes(answer, freq, fill = answer)) + geom_bar(stat = "identity") + theme_bw() 

enter image description here

注:如果您有关于其他问题( “Q2_1”, “Q2_2” ...)更多的列可能是更加复杂。在这种情况下,为每个问题解释数据可能是一个解决方案。

+0

谢谢,更正。 – bVa

0

我想你想是这样的(比例与堆积条形图):

Participant Q1_1 Q1_2 Q1_3 
1   1 a   c 
2   2 a a c 
3   3 c b c 
4   4   b d 

# ensure that all question columns have the same factor levels, ignore blanks 
for (i in 2:4) { 
    df[,i] <- factor(df[,i], levels = c(letters[1:4])) 
} 

tdf <- as.data.frame(sapply(df[2:4], function(x)table(x)/sum(table(x)))) 
tdf$choice <- rownames(tdf) 
tdf <- melt(tdf, id='choice') 

ggplot(tdf, aes(variable, value, fill=choice)) + 
     geom_bar(stat='identity') + 
     xlab('Questions') + 
     ylab('Proportion of Choice') 

enter image description here