Marco Dinatsoli
Marco Dinatsoli

Reputation: 10570

R how to add a second label for a matrix

I want to build this matrixenter image description here

What I tried

table <- matrix(c(163,224,312,314,303,175,119,662,933,909,871,702,522,307,1513,2400,2164,2299,1824,1204,678,1603,2337,2331,2924,2360,1428,808,2834,3903,3826,4884,3115,2093,89), nrow=5, ncol=7, byrow=T)

rownames(table) <- c("Fair", "Good", "Very Good", "Premium", "Ideal")

 colnames(table) <- c("D", "E", "F", "G", "H", "I", "J")

but the result is this:

enter image description here

and my question is how to add the color and cut labels

Upvotes: 5

Views: 75

Answers (1)

akrun
akrun

Reputation: 887203

Here, dimnames(table) is a 'list'. In the original matrix 'table', the list elements are not named. We can use names to change the names of the list from 'NULL' to the preferred one.

names(dimnames(table)) <- c('cut', 'color')
table
#          color
# cut          D    E    F    G    H    I   J
#  Fair       163  224  312  314  303  175 119
#  Good       662  933  909  871  702  522 307
#  Very Good 1513 2400 2164 2299 1824 1204 678
#  Premium   1603 2337 2331 2924 2360 1428 808
#  Ideal     2834 3903 3826 4884 3115 2093  89

NOTE: table is an R function, so it is better to name the object a different name.

Upvotes: 7

Related Questions