2016-11-29 128 views
0

我想通过计算每个变量在案例和控件中出现或缺失的次数来为几个不同的变量var1PA,var2PA绘制分组堆积的条形图。在堆积分组的条形图中计算变量百分比

df <- data.frame(SampleID = c(1, 2, 3, 4, 5, 6, 7, 8), 
     Var1 = c(0.1 , 0.5, 0.7, 0, 0, 0, 0.5, 0.2), 
     Var1PA = c("Present", "Present", "Present", "Absent", "Absent", "Absent", "Present", "Present"), 
     Var2 = c(0, 0, 0, 0, 0.1, 0.5, 0.7, 0.2), 
     Var2PA = c("Absent", "Absent", "Absent", "Absent", "Present", "Present", "Present", "Present"), 
     Disease = c("Case", "Control", "Case", "Control", "Case", "Control", "Case", "Control")) 

我想计算的当前百分比,并没有对每种情况和各变种中的每个控制却无法使用道具表做,

vars <- c('Var1PA', 'Var2PA') 
    tt <- data.frame(prop.table(as.table(sapply(df[, vars], table)), 2) * 100) 
##above line does not calculate the percentage of present absent individually for cases 
##and controls within each var 

,如果我能做到这一点,然后我可以用GGPLOT2绘制:

ggplot(tt, aes(Disease, Freq)) + 
geom_bar(aes(fill = Var1), position = "stack", stat="identity") + facet_grid(~vars) 

如何获得每个瓦尔的病例(在场与不在场)和对照组(存在和不存在)的百分比?谢谢!

回答

1

这是最后一个问题的一个相当简单的扩展。在获取数据到长格式,我们把Disease就像SampleID,否则代码是相同的:

library(ggplot2) 
library(tidyr) 
library(dplyr) 
mdf = df %>% select(SampleID, Disease, ends_with("PA")) %>% 
    gather(key = Var, value = PA, -SampleID, -Disease) %>% 
    mutate(PA = factor(PA, levels = c("Present", "Absent"))) 

然后我们就可以直接进入剧情依靠ggplot计算百分比。这与上一个问题的情节完全相同,但x轴上的Disease和添加了刻面。

ggplot(mdf, aes(Disease)) + 
    geom_bar(aes(fill = PA), position = "fill") + 
    scale_y_continuous(labels = scales::percent) + 
    facet_grid(~Var) 

如果你想在数据帧中的百分比,我们可以做到这一点多一点的操作:

df_summ = mdf %>% group_by(Disease, Var) %>% 
    mutate(n = n()) %>% ## calculate n for Disease and Var groups 
    group_by(Disease, Var, PA) %>% 
    summarize(Percent = n()/first(n)) ## calculate the fraction P/A in each group 

随着该汇总的数据帧,我们可以创建同积如上更明确:

ggplot(df_summ, aes(Disease, Percent)) + 
    geom_bar(aes(fill = PA), position = "stack", stat = "identity") + 
    scale_y_continuous(labels = scales::percent) + 
    facet_grid(~Var) 
+0

嗨,格里高尔,感谢您的解决方案!非常酷的使用dplyr和tidyr函数。一个简单的问题,负号“-SampleID -Disease”表示什么?我之前也没有见过'%>%'的大量使用。这是为了避免命名多个新的中间dfs? –

+0

嗨格里高,快速的问题,在你的代码中,可以'ends_with(“PA”)'替换为更像泛型的字符串向量。假设我提供了 'vars = c(“Var1”,“Var2”,“Var3”)',可以'select'使用这个向量吗?我有多个以PA结尾的变量,我想选择性地只绘制其中的几个变量。谢谢!,Manasi –

+0

我在使用'one_of(vars)'的文档中找到了一个解决方案'如果有人读过这个链! –

0

试试这个:

ggplot(tt, aes(Var2, Freq, fill=Var1)) + geom_bar(stat='identity') + 
    xlab('Variable') + guides(fill=guide_legend("Variable")) 

enter image description here