您可以简单地spread
指定数据并运行该table
功能dnn
library(dplyr) library(tidyr) dta %>% spread(sexe, dip14_rec) %>% select(-idmen) %>% table(., dnn = c("Men", "Women")) # Women # Men No Diploma Primary-Secondary Uni # No Diploma 0 0 1 # Primary-Secondary 0 2 0 # Uni 0 1 1
或类似的 data.table
library(data.table) # V 1.9.6+ dcast(setDT(dta), idmen ~ sexe)[, table(Men = `1`, Women = `2`)] # Using 'dip14_rec' as value column. Use 'value.var' to override # Women # Men No Diploma Primary-Secondary Uni # No Diploma 0 0 1 # Primary-Secondary 0 2 0 # Uni 0 1 1
数据
dta <- structure(list(idmen = c(110008218L, 110008218L, 110010366L, 110010366L, 110011567L, 110011567L, 110012163L, 110012163L, 110016580L, 110016580L), sexe = c(1L, 2L, 1L, 2L, 1L, 2L, 2L, 1L, 2L, 1L), dip14_rec = structure(c(3L, 2L, 3L, 3L, 2L, 2L, 2L, 2L, 3L, 1L), .Label = c("No Diploma", "Primary-Secondary", "Uni"), class = "factor")), .Names = c("idmen", "sexe", "dip14_rec"), class = "data.frame", row.names = c("1", "2", "3", "4", "5", "6", "7", "8", "9", "10"))