I want to take one row of matrix M and treat the row as a named vector, with the column names of the original matrix as the names of the vector. Usually M[x, ] does what I want but this fails if:
(a) the rows of the matrix are named, and
(b) the number of columns is 1.
I can work around this, but it seems inelegant. What is the purpose of this behaviour (and in particular why does it make any difference that the rows are named)?
Examples:
M <- structure(c(72L, 92L, 81L, 81L, 87L, 76L, 89L, 70L, 70L, 73L,
74L, 75L), .Dim = 4:3, .Dimnames = list(c("SeptQuiz", "Midterm",
"NovQuiz", "Final"), c("Anne", "Bo", "Cameron"))) # multiple columns, rows are named
(v1 <- M[3, ]) # subsetting one row, as a vector, preserves student names
M <- structure(c(91L, 87L, 83L, 81L), .Dim = c(4L, 1L), .Dimnames = list(
NULL, "Frank")) # one column, rows are unnamed
(v1 <- M[3, ]) # again, subsetting one row as a vector preserves student name
M <- structure(c(91L, 87L, 83L, 81L), .Dim = c(4L, 1L), .Dimnames = list(
c("SeptQuiz", "Midterm", "NovQuiz", "Final"), "Frank")) # one column, rows are named
(v1 <- M[3, ]) # subsetting one row deletes student name
if(ncol(M) == 1 && !is.null(rownames(M))) {names(v1) <- colnames(M)} # kludge to restore student name if it was stripped