我想知道
tableone package
data$sex <- factor(data$sex) # note that you will have to ensure these are factors
data$country <- factor(data$country)
library(tableone)
tab1 <- CreateTableOne(vars=c("sex", "country"), strata="job", data=data)
print(tab1, showAllLevels=TRUE, test=FALSE, explain=FALSE)
# Stratified by job
# level 11 12 13
# n 2 2 1
# sex 0 2 (100.0) 0 ( 0.0) 1 (100.0)
# 1 0 ( 0.0) 2 (100.0) 0 ( 0.0)
# country 1 1 ( 50.0) 0 ( 0.0) 1 (100.0)
# 2 0 ( 0.0) 2 (100.0) 0 ( 0.0)
# 3 1 ( 50.0) 0 ( 0.0) 0 ( 0.0)
如果您想进行后续处理,上述解决方案将不太可行。这是一个编码的解决方案,但您必须针对每种情况进行调整:
out.data <- t(sapply(split(data, job), function(df){
with(df, c(table(sex), table(country))) }))
out.data <- data.frame(job=rownames(out.data), out.data)
rownames(out.data) <- NULL
colnames(out.data)[2:6] <- c(paste("sex", levels(data$sex), sep="_"),
paste("country", levels(data$country), sep="_") )
out.data
# job sex_0 sex_1 country_1 country_2 country_3
# 1 11 2 0 1 0 1
# 2 12 0 2 0 2 0
# 3 13 1 0 1 0 0