To summarize each variable in my data, I typically create two tables: one that groups by experimental condition and a second that displays aggregated statistics across all experimental groups.
However, I'd like to display both grouped and aggregated descriptives in a single table.
I've accomplished this as shown below in the demo code — however, I'd like to find a more elegant solution, ideally using a single chain.
Does anyone know how I might accomplish this?
Thank for your help.
# Data
df <- tibble(Condition = rep(c("Group1",
"Group2",
"Group3",
"Group4"),20),
comp_fail = rbinom(n = 80,
size = 1,
prob = .1)
)
# Converting Condition to factor to mimic my actual df
df$Condition <- as.factor(df$Condition)
# Descriptives grouped by condition
tbl_comp_fail_condition <-
df %>%
group_by(Condition) %>%
summarize("# with Zero Fails" = sum(comp_fail == 0, na.rm = T),
"# with One Fail" = sum(comp_fail == 1, na.rm = T))
# Descriptives aggregated
tbl_comp_fail_aggregate <-
df %>%
summarize("# with Zero Fails" = sum(comp_fail == 0, na.rm = T),
"# with One Fail" = sum(comp_fail == 1, na.rm = T))
# Joining grouped and aggregated
tbl_comp_fail_combined <- full_join(
tbl_comp_fail_aggregate,
tbl_comp_fail_condition) %>%
select(Condition, everything())
# Converting Condition to character to replace NA with All
tbl_comp_fail_combined$Condition <- as.character(tbl_comp_fail_combined$Condition)
# Replace NA with All
tbl_comp_fail_combined %>% replace_na(list(Condition = "All")) ``