name
name

Reputation: 235

How to order contingency table based on data order?

Given

Group    ss
B        male
B        male
B        female
A        male
A        female
X        male

Then

tab <- table(res$Group, res$ss)

I want the group column to be in the order B, A, X as it is on the data. Currently its alphabetic order which is not what I want. This is what I want

   MALE  FEMALE
B  5     5
A  5     10
X  10    12

Upvotes: 0

Views: 468

Answers (2)

George Savva
George Savva

Reputation: 5336

unique returns the unique elements of a vector in the order they occur. A table can be ordered like any other structure by extracting its elements in the order you want. So if you pass the output of unique to [,] then you'll get the table sorted in the order of occurrence of the vector.

tab <- table(res$Group, res$ss)[unique(res$Group),]

Upvotes: 0

Ronak Shah
Ronak Shah

Reputation: 389175

If you arrange the factor levels based on the order you want, you'll get the desired result.

res$Group <- factor(res$Group, levels = c('B', 'A', 'X'))
#If it is based on occurrence in Group column we can use 
#res$Group <- factor(res$Group, levels = unique(res$Group))
table(res$Group, res$ss)
#Or just
#table(res)

#    female male
#  B      1    2
#  A      1    1
#  X      0    1

data

res <- structure(list(Group = structure(c(2L, 2L, 2L, 1L, 1L, 3L), 
.Label = c("A", "B", "X"), class = "factor"), ss = structure(c(2L, 2L, 1L, 2L, 
1L, 2L), .Label = c("female", "male"), class = "factor")), 
class = "data.frame", row.names = c(NA, -6L))

Upvotes: 1

Related Questions