Blake S.
Blake S.

Reputation: 411

Add column sum to table

Data structure is:

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

I'm using table(df$Company,df$Marital), but I want to have a column that shows the row total, such as the following:

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

Is there a different table function that provides a row sum append option?

Upvotes: 26

Views: 65950

Answers (4)

Sam Firke
Sam Firke

Reputation: 23004

The tabyl function from the janitor package does exactly that. With your data:

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

Self-promotion disclosure: I wrote and maintain this package. Posting this answer as the question asks about alternative approaches to table() that support adding totals - which is precisely what tabyl() does.

Upvotes: 5

Nettle
Nettle

Reputation: 3321


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

Upvotes: 6

David Robinson
David Robinson

Reputation: 78590

You could use cbind and rowSums afterwards:

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

You can also use the built-in addmargins function:

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

(The 2 means to add a sum column, but not a sum row- you can omit it and you'll get both).

Upvotes: 45

Jilber Urbina
Jilber Urbina

Reputation: 61154

You can use addmargins

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

Upvotes: 17

Related Questions