开发者

Create table with subtotal per row and per column

开发者 https://www.devze.com 2023-01-28 08:08 出处:网络
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)

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开发者_JAVA技巧 1 1 1 1 4
  3 1 1 1 1 4
    3 3 3 3


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

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号