0

i want to have the total cases in header itself with in the table. so the total number of responses can be included in table.

i want to have spss table type so i a using expsss here

df <- data.frame("TB1"=c("OPS", "OPS",  "HR",   "ADMIN",    "HR",   "ADMIN",    "ADMIN",    "HR",   "HR",   "HR",   "Sales",    "Sales",    "Sales",    "HR",   "HR",   "HR",   "HR",   "Sales",    "Sales"),
                 "TB2"=c("Sales",   "ADMIN",    "ADMIN",    "Sales",    "ADMIN",    "ADMIN",    "ADMIN",    "HR",   "HR",   "HR",   "HR",   "HR",   "HR",   "OPS",  "OPS",  "OPS",  "OPS",  "HR",   "HR"),
                 "TB3"=c("ADMIN",   "Sales",    "OPS",  "Sales",    "HR",   "ADMIN",    "HR",   "HR",   "ADMIN",    "ADMIN",    "HR",   "HR",   "HR",   "OPS",  "HR",   "OPS",  "HR",   "HR",   "Sales"),
                 "TB4"=c("Global",  "Regional", "Regional", "Global",   "Global",   "Regional", "Regional", "Global",   "Global",   "Regional", "Regional", "Global",   "Global",   "Regional", "Global",   "Regional", "Global",   "Regional", "Global"))



banner <- with(df, list(total(),TB4))

t1 <-  tab1 <- expss::cro_cpct(df$TB1, banner)

the output should be look like below

enter image description here

coder2learn
  • 165
  • 6

2 Answers2

0

Using the dplyr and tidyr packages:

library(dplyr)
library(tidyr)

## Create table as data frame
tab <- df %>%
  group_by(TB4, TB1) %>%
  tally() %>%
  pivot_wider(names_from = TB4, values_from = n) %>%
  mutate(Total = Global + Regional, .before = Global) %>%
  mutate_if(is.numeric, function(x) round(x/sum(x)*100,0))

## Rename column names
totals <- table(df$TB4)
totals <- c(sum(totals), totals)
names(tab) <- c("row_labels", paste0(names(tab)[-1], " (total = ",totals,")"))

tab
# # A tibble: 4 × 4
#   row_labels `Total (total = 19)` `Global (total = 10)` `Regional (total = 9)`
#   <chr>                     <dbl>                 <dbl>                  <dbl>
# 1 ADMIN                        16                    10                     22
# 2 HR                           47                    50                     44
# 3 OPS                          11                    10                     11
# 4 Sales                        26                    30                     22

DrEspresso
  • 211
  • 5
0

Using your table created with package expss:

totals <- table(df$TB4)
totals <- c(sum(totals), totals)
names(t1) <- c("row_labels", paste0(names(t1)[-1], " (total = ",totals,")"))
DrEspresso
  • 211
  • 5
  • actually table is being created dynamically for banner and totals <- table(df$TB4) ,TB4 can be any column so needed to make it dynamically, but still there is a scope we can change something – coder2learn Apr 19 '23 at 12:54