【问题标题】:R Keep colnames and rownames when using sapply on a matrixR 在矩阵上使用 sapply 时保留列名和行名
【发布时间】:2020-01-25 15:32:09
【问题描述】:

在应用applysapplyhere 时,已经提出了一个问题,即如何将列名保存在矩阵中。 但我没有找到如何保留矩阵的列 AND 行名。

下面是一个例子:

mat = matrix(c(as.character(1:4)), nrow = 2)
colnames(mat) = c( 'col1', 'col2' )
rownames(mat) = c( 'row1', 'row2' )
mat = apply(mat,  2,  function(x) as.numeric(paste(x)))
colnames(mat)
rownames(mat)

提前致谢:-)

【问题讨论】:

  • this 问题及其答案可能值得一看

标签: r dataframe matrix apply sapply


【解决方案1】:

我们可以将您的应用程序包装在用户定义的函数中。

mat_fun <- function(m){
  m2 <- apply(m,  2,  function(x) as.numeric(paste(x)))
  colnames(m2) <- colnames(m)
  rownames(m2) <- rownames(m)
  return(m2)
}

mat_fun(mat)
#      col1 col2
# row1    1    3
# row2    2    4

【讨论】:

  • 非常聪明!他不得不思考。非常感谢;-)
【解决方案2】:

如果您使用 [] 重新分配,名称将被保留。不幸的是,这仅在您不想创建新矩阵并且不想更改元素的类(例如,本例中从字符到数字)时才有用

mat[] <- apply(mat,  2,  function(x) 1 + as.numeric(paste(x)))
mat
#      col1 col2
# row1 "2"  "4" 
# row2 "3"  "5" 

【讨论】:

  • 感谢您的精确。这种方法在某些操作上可能非常有用。
猜你喜欢
  • 2023-03-15
  • 2021-12-17
  • 2013-03-25
  • 1970-01-01
  • 2019-05-31
  • 1970-01-01
  • 2020-10-07
  • 2014-01-26
  • 2014-11-20
相关资源
最近更新 更多