如果您提供实际数据的样本,您会得到更好的答案(请参阅
this post
). 也就是说,这里有一个使用
dplyr::
(和
reshape2::melt
).
# function to create a column of fake data
make_var <- function(n=100) sample(c("good","bad","ugly"), size=n, replace=TRUE)
# put ten of them together
dat <- as.data.frame(replicate(10, make_var()), stringsAsFactors=FALSE)
library("dplyr")
# then reshape to long format, group, and summarize --
dat %>% reshape2::melt(NULL) %>% group_by(variable) %>% summarize(
good_pct = (sum(value=="good") / length(value)) * 100,
bad_pct = (sum(value=="bad") / length(value)) * 100,
ugly_pct = (sum(value=="ugly") / length(value)) * 100
)
请注意,要按另一列(例如性别)分组,您可以说
group_by(variable, sex)
在总结之前(只要
sex
是一列数据,但在这个构造的示例中并非如此)。