【问题标题】:setNames for rows and columns?为行和列设置名称?
【发布时间】:2017-06-11 04:31:43
【问题描述】:

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

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

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

【问题讨论】:

  • 也许"dimnames&lt;-"(m, list(rownames, colnames)) ?

标签: r matrix row


【解决方案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'))))

【讨论】:

    猜你喜欢
    • 2015-05-24
    • 1970-01-01
    • 2021-09-30
    • 1970-01-01
    • 2020-04-07
    • 1970-01-01
    • 2014-04-01
    • 1970-01-01
    • 2019-09-14
    相关资源
    最近更新 更多