这是一个base R。使用rowSums 在仅选择“Var”列的逻辑矩阵上获取“是”的计数,然后按“性别”进行分组以使用rowsum 按性别汇总计数并使用barplot
barplot(t(rowsum(rowSums(df1[-1] == 'Yes'), df1$Sex)))
或者如果我们需要按条形图进行分组,请将其更改为
barplot(t(rowsum(+(df1[-1] == 'Yes'), df1$Sex)), beside = TRUE,
legend = TRUE, col = c('red', 'blue', 'green'))
或者,如果我们更喜欢ggplot,则使用pivot_longer(来自tidyr)重塑为“长”格式,获取group_by,summarise 以返回“是”的计数并使用ggplot
library(dplyr)
library(tidyr)
library(ggplot2)
df1 %>%
pivot_longer(cols = -Sex) %>%
group_by(Sex) %>%
summarise(n = sum(value == 'Yes')) %>%
ggplot(aes(x = Sex, y = n)) +
geom_col()
对于每个 'Var' 的条形
df1 %>%
pivot_longer(cols = -Sex) %>%
group_by(Sex, name) %>%
summarise(n = sum(value == 'Yes'), .groups = 'drop') %>%
ggplot(aes(x = Sex, y = n, fill = name)) +
geom_col(position = 'dodge')
-输出
数据
df1 <- structure(list(Sex = c("Male", "Female", "Male", "Female"),
Var1 = c("Yes",
"No", "No", "Yes"), Var2 = c("No", "Yes", "No", "Yes"), Var3 = c("Yes",
"No", "Yes", "No")), class = "data.frame", row.names = c(NA,
-4L))