2016-11-29 125 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