R语言 获取表中表头的频率

zi8p0yeb  于 2023-04-27  发布在  其他
关注(0)|答案(2)|浏览(107)

我想有标题本身在表中的总情况下。因此,响应的总数可以包括在表中。
我想有spss表类型,所以我在这里使用expsss

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)

输出应如下所示

jq6vz3qz

jq6vz3qz1#

使用dplyrtidyr包:

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
wlsrxk51

wlsrxk512#

使用使用expss包创建的表:

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

相关问题