Using the expss package, I'm trying to create a table with nested rows and columns. Let's say I have a df of the following structure: Each observation refers to a participant who either sits in group A or B. The participants answer one or more of 4 items which they can (partially) pass or fail. In addition, there are different trials.
Here some dummy data:
set.seed(321)
test <- tibble(
trial = rep(c("Trial_A", "Trial_B"), each = 6),
group = rep(c("A", "B"), each = 6),
result = rep(c("Fail", "Pass", "Partial Pass"), times = 4),
item = rep(c("item 1", "item 2", "item 3", "item 4"), each = 3)) %>%
tidyr::expand(trial, group, result, item) %>%
mutate(count = round(runif(n = 48, min = 0, max = 10))) %>%
uncount(count)
I'm now trying to create a table that displays the row percentage for the results nested within each group (A or B). Those should be my the columns. The rows are the four items, nested within the different trials. I can manage to get row percentages within the groups, but my rows are unnecessarily doubled. How can I prevent that from happening?
test %>%
tab_cells(item) %>%
tab_cols(group %nest% result) %>%
tab_rows(trial) %>%
tab_subgroup(group =="A") %>%
#tab_stat_cases(label = "N", total_label = "") %>%
tab_stat_rpct(total_row_position = "above", label="%", total_label = "", total_statistic = c("u_rpct")) %>%
tab_subgroup(group =="B") %>%
#tab_stat_cases(label = "N", total_label = "") %>%
tab_stat_rpct(total_row_position = "above", label="%", total_label = "", total_statistic = c("u_rpct")) %>%
tab_pivot(stat_position = "inside_rows")
The edit of this solution works partially for me but somehow creates for each column an additional empty column. So not sure what's going on. In addition, I would like to include two extra columns (before the answer columns) with the total count of observations per row/group.
| | | | | | A | | | B | | |
| | | | | | Fail | Partial Pass | Pass | Fail | Partial Pass | Pass |
| ----- | ------- | ---- | ------ | -- | ---- | ------------ | ---- | ---- | ------------ | ---- |
| trial | Trial_A | item | # | % | 38.7 | 24.2 | 37.1 | | | |
| | | | | | | | | 24.6 | 29.2 | 46.2 |
| | | | item 1 | % | 52.6 | 21.1 | 26.3 | | | |
| | | | | | | | | 40.0 | 30.0 | 30.0 |
| | | | item 2 | % | 45.0 | 15.0 | 40.0 | | | |
| | | | | | | | | | 28.6 | 71.4 |
| | | | item 3 | % | 15.4 | 38.5 | 46.2 | | | |
| | | | | | | | | 33.3 | 16.7 | 50.0 |
| | | | item 4 | % | 30.0 | 30.0 | 40.0 | | | |
| | | | | | | | | 15.4 | 46.2 | 38.5 |
| | Trial_B | item | # | % | 38.9 | 22.2 | 38.9 | | | |
| | | | | | | | | 29.2 | 38.5 | 32.3 |
| | | | item 1 | % | 42.9 | 7.1 | 50.0 | | | |
| | | | | | | | | 30.4 | 34.8 | 34.8 |
| | | | item 2 | % | 33.3 | 25.0 | 41.7 | | | |
| | | | | | | | | | 50.0 | 50.0 |
| | | | item 3 | % | 52.6 | 10.5 | 36.8 | | | |
| | | | | | | | | 53.8 | 38.5 | 7.7 |
| | | | item 4 | % | 26.7 | 46.7 | 26.7 | | | |
| | | | | | | | | 21.7 | 39.1 | 39.1 |