Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

setNames for rows and columns?

Tags:

r

matrix

row

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?

like image 977
ApproachingDarknessFish Avatar asked Sep 08 '25 11:09

ApproachingDarknessFish


1 Answers

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'))))
like image 135
ApproachingDarknessFish Avatar answered Sep 10 '25 05:09

ApproachingDarknessFish