用 expss 解决。我认为代码不是很简洁:
library(expss)
df = data.frame(ID=c(1,2,3,4,5,6),
Treat_Cont = c("Treatment", "Treatment", "Treatment", "Control", "Control", "Control"),
Q1 = c("Yes", "No", NA, "Yes", "No", NA),
Q2 = c("Yes", "No", NA, "Yes", "No", NA)
)
df %>%
tab_total_row_position("none") %>% # suppress totals
tab_rows("|" = Treat_Cont) %>% # "|" suppress var. labels
tab_cols(total(label = "|")) %>% # "|" suppress var. labels
# if_na add values for NA
tab_cells("|" = if_na(Q1, "<NA>")) %>% # "|" suppress var. labels
tab_stat_cases(label = "Q1") %>% # calculate stats
tab_cells("|" = if_na(Q1, "<NA>")) %>% # "|" suppress var. labels
tab_stat_cases(label = "Q2") %>% # calculate stats
tab_pivot(stat_position = "inside_columns") %>% # labels reposition
tab_transpose() # transpose table
更新:更短的解决方案。
df %>%
calculate(
cro(Treat_Cont %nest% if_na(Q1, "<NA>"), list("Q1"), total_row_position = "none") %merge%
cro(Treat_Cont %nest% if_na(Q2, "<NA>"), list("Q2"), total_row_position = "none")
) %>%
tab_transpose()
以 R 为底的短解:
with(df,
rbind(
"Q1" = table(Treat_Cont:addNA(Q1)),
"Q2" = table(Treat_Cont:addNA(Q2))
))