行和列的setNames?

时间:2017-01-25 20:23:18

标签: r matrix row

我正在尝试编写一个返回带有命名行和列的矩阵的函数,我正在寻找一个比以下更简洁的解决方案:

m <- get_matrix()
rownames(m) <- c('the', 'row', 'names')
colnames(m) <- c('the', 'col', 'names')
return (m)

我最近了解了setNames function,它创建了一个名称设置的矢量或列表的副本。这正是我需要的那种功能,但它不适用于matrix.是否有像setNames这样的函数适用于二维数据类型?

1 个答案:

答案 0 :(得分:1)

使用structure功能设置dimnames attribute

return (structure(get_matrix(), dimnames=list(c('the', 'row', 'names'), c('the', 'col', 'names'))))

仅设置行名称:

return (structure(get_matrix(), dimnames=list(c('the', 'row', 'names'))))

仅设置列名称:

return (structure(get_matrix(), dimnames=list(NULL, c('the', 'col', 'names'))))