Jeff Bezos
Jeff Bezos

Reputation: 2253

Subset R table dimensions by name

I have a 3D table() output. How do I subset a 2D table by name?

dim1 <- LETTERS
dim2 <- letters
dim3 <- 1:26
tbl <- table(dim1, dim2, dim3)
names(attr(tbl, "dimnames")) # dim1, dim2 dim3

table(dim1, dim2) # how do I get this output without redoing the tabulation?

Upvotes: 0

Views: 60

Answers (1)

dcarlson
dcarlson

Reputation: 11046

You want to use margin.table or marginSums. The two functions are the same. The second is more descriptive, but the first was the original name. To collapse the 3 dimensional array to 2 dimensions:

margin.table(tbl, c("dim1", "dim2"))   # Or margin.table(tbl, 1:2)

will give you the same as

table(dim1, dim2)

Upvotes: 2

Related Questions