Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add column sum to table

Tags:

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?

like image 382
Blake S. Avatar asked Jan 15 '15 17:01

Blake S.


People also ask

How do I sum a column in a table in Excel?

Navigate to the Home tab -> Editing group and click on the AutoSum button. You will see Excel automatically add the =SUM function and pick the range with your numbers. Just press Enter on your keyboard to see the column totaled in Excel.

How do you add a column sum?

If you need to sum a column or row of numbers, let Excel do the math for you. Select a cell next to the numbers you want to sum, click AutoSum on the Home tab, press Enter, and you're done. When you click AutoSum, Excel automatically enters a formula (that uses the SUM function) to sum the numbers.


2 Answers

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).

like image 177
David Robinson Avatar answered Oct 20 '22 09:10

David Robinson


You can use addmargins

x <- table(df$Company,df$Marital) addmargins(x)         # option 1 ftable(addmargins(x)) # option 2 
like image 45
Jilber Urbina Avatar answered Oct 20 '22 09:10

Jilber Urbina