[R] cannot assign dimnames
Gabor Grothendieck
ggrothendieck at myway.com
Mon Sep 27 17:39:09 CEST 2004
Dan Bebber <danbebber <at> forestecology.co.uk> writes:
: If anyone knows how to assign dimnames to matrices or arrays I would be most
: grateful for help. I've tried various permutations of likely-looking code
: but get error messages every time. I could find no example in the
: documentation.
Here are 4 ways of assigning dimnames to a matrix.
# matrix - 1
mat1 <- matrix(1:12,4,3, dimnames = list(letters[1:4], LETTERS[1:3]))
# matrix - 2
mat2 <- matrix(1:12,4,3)
dimnames(mat2) <- list(letters[1:4], LETTERS[1:3])
# matrix - 3
mat3 <- matrix(1:12,4,3)
attr(mat3, "dimnames") <- list(letters[1:4], LETTERS[1:3])
# matrix - 4
mat4 <- matrix(1:12,4,3)
rownames(mat4) <- letters[1:4]
colnames(mat4) <- LETTERS[1:3]
# For arrays its similar, e.g. here is #1 redone for an array:
arr <- array(1:24, c(2,3,4),dimnames=list(letters[1:2],LETTERS[1:3],month.abb
[1:4]))
# For a data frame the various forms above also work except that
# (a) this form is also available
DF <- data.frame(A = 1:4, B = 5:8, C = 9:12, row.names = letters[1:4])
# and (b) for data frames one must use row.names in place of
# rownames though colnames still works as does names (which works
# like colnames)
More information about the R-help
mailing list