Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create table with subtotal per row and per column

Tags:

r

I know how to create table in R using table, like this:

x <- rep(1:3,4)
y <- rep(1:4,3)
z<- cbind(x,y)
table(z[,1],z[,2])

    1 2 3 4
  1 1 1 1 1
  2 1 1 1 1
  3 1 1 1 1

How can I add the margin total of the table to making it looks like:

    1 2 3 4
  1 1 1 1 1 4
  2 1 1 1 1 4
  3 1 1 1 1 4
    3 3 3 3
like image 706
lokheart Avatar asked Dec 06 '10 07:12

lokheart


People also ask

Can you subtotal in a table?

You can automatically calculate subtotals and grand totals in a list for a column by using the Subtotal command. Important: Subtotals are not supported in Excel tables. The Subtotal command will appear grayed out if you are working with an Excel table.


1 Answers

> a
     [,1] [,2] [,3]
[1,]    1    1    1
[2,]    1    1    1
[3,]    1    1    1

> a <- cbind(a, rowSums(a))
> a <- rbind(a, colSums(a))
> a
     [,1] [,2] [,3] [,4]
[1,]    1    3    1    5
[2,]    1    1    1    3
[3,]    1    1    1    3
[4,]    3    5    3   11

Another approach:

a <- addmargins(a, c(1, 2), sum)
like image 176
Roman Luštrik Avatar answered Sep 18 '22 14:09

Roman Luštrik