将列总和添加到 table

Add column sum to table

数据结构为:

Company        Marital
a              single
a              married
b              widow
c              married
b              single

我正在使用 table(df$Company,df$Marital),但我想要一个显示行总数的列,例如:

            a     b    c    Total
married     50    20   5    75
single      10    10   10   30
widow       5     50   0    55

是否有不同的 table 函数提供行求和追加选项?

之后您可以使用 cbindrowSums

tab <- table(df$Company,df$Marital)
tab <- cbind(tab, Total = rowSums(tab))

您还可以使用内置的addmargins函数:

tab <- addmargins(table(df$Company,df$Marital), 2)

2 表示添加总和列,而不是总和行 - 您可以省略它,两者都会得到)。

您可以使用addmargins

x <- table(df$Company,df$Marital)
addmargins(x)         # option 1
ftable(addmargins(x)) # option 2


library(dplyr)

df <- tribble(
        ~status,      ~a,    ~b,  ~c,
        "married",     50,    20,   5,
        "single",      10,    10,  10,
        "widow",       5,     50,   0
        )

df %>% 
  mutate(Total_Row = rowSums(.[2:4]))
#> # A tibble: 3 x 5
#>   status      a     b     c Total_Row
#>   <chr>   <dbl> <dbl> <dbl>     <dbl>
#> 1 married 50.0   20.0  5.00      75.0
#> 2 single  10.0   10.0 10.0       30.0
#> 3 widow    5.00  50.0  0         55.0

df %>% 
  mutate(Total_Row = select(., 2:4) %>% rowSums())
#> # A tibble: 3 x 5
#>   status      a     b     c Total_Row
#>   <chr>   <dbl> <dbl> <dbl>     <dbl>
#> 1 married 50.0   20.0  5.00      75.0
#> 2 single  10.0   10.0 10.0       30.0
#> 3 widow    5.00  50.0  0         55.0

janitor 包中的 tabyl 函数就是这样做的。使用您的数据:

library(janitor)
dat %>%
  tabyl(Marital, Company) %>%
  adorn_totals("col")

 Marital a b c Total
 married 1 0 1     2
  single 1 1 0     2
   widow 0 1 0     1

自我推销披露:我编写并维护了这个包。 发布这个答案作为问题询问 table() 的替代方法,支持添加总计 -这正是 tabyl() 所做的。