我想通过计算每个变量在案例和控件中出现或缺失的次数来为几个不同的变量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)
如何获得每个瓦尔的病例(在场与不在场)和对照组(存在和不存在)的百分比?谢谢!
嗨,格里高尔,感谢您的解决方案!非常酷的使用dplyr和tidyr函数。一个简单的问题,负号“-SampleID -Disease”表示什么?我之前也没有见过'%>%'的大量使用。这是为了避免命名多个新的中间dfs? –
嗨格里高,快速的问题,在你的代码中,可以'ends_with(“PA”)'替换为更像泛型的字符串向量。假设我提供了 'vars = c(“Var1”,“Var2”,“Var3”)',可以'select'使用这个向量吗?我有多个以PA结尾的变量,我想选择性地只绘制其中的几个变量。谢谢!,Manasi –
我在使用'one_of(vars)'的文档中找到了一个解决方案'如果有人读过这个链! –