我想计算分类数据的百分比。
我有以下数据集。
library(tidyverse)
tib <- tibble(a = c("yes", "yes", "yes", "yes"),
b = c("yes", "yes", "no", "yes"),
c = c("AB", "yes", "AC", "no"),
d = c("AC", "yes", "no", "AB"),
) space = c("UP", "DO", "UP", "TA")
例如,如果我们想了解“a”:
df_perc <- as.data.frame(prop.table(table(tib$space, tib$a)) * 100)
Var1 Var2 Freq
1 DO yes 25
2 TA yes 25
3 UP yes 50
这是正确的。
现在,为了避免对每一列都这样做,我尝试使用gather:
df_tidy <- tib %>%
gather(key="let", value="response", -"space")
然后这样做:
df_perc <- as.data.frame(prop.table(table(df_tidy$let, df_tidy$response)) * 100)