Reputation: 14323
I'm trying to write a function that returns a matrix with named rows and columns, and I'm looking for a more succinct solution than:
m <- get_matrix()
rownames(m) <- c('the', 'row', 'names')
colnames(m) <- c('the', 'col', 'names')
return (m)
I recently learned about the setNames function, which creates a copy of a vector or list with its names set. This is exactly the sort of functionality I need, but it doesn't work for matrix.
Is there a function like setNames
that works for two-dimensional data types?
Upvotes: 4
Views: 1949
Reputation: 14323
Use the structure function to set the dimnames attribute:
return (structure(get_matrix(), dimnames=list(c('the', 'row', 'names'), c('the', 'col', 'names'))))
To set only row names:
return (structure(get_matrix(), dimnames=list(c('the', 'row', 'names'))))
To set only column names:
return (structure(get_matrix(), dimnames=list(NULL, c('the', 'col', 'names'))))
Upvotes: 3