R 在矩阵上使用 sapply 时保留列名和行名
R Keep colnames and rownames when using sapply on a matrix
关于在应用 apply
、sapply
等 时如何将列名保留在矩阵中的问题已经提出。
但是我没有找到如何保留列 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)
提前致谢:-)
我们可以将您的应用程序包装在用户定义的函数中。
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
如果您使用 []
重新分配,名称将被保留。不幸的是,这仅在您不想创建新矩阵并且不想更改元素的 class 时才有用(例如,从本例中的字符到数字)
mat[] <- apply(mat, 2, function(x) 1 + as.numeric(paste(x)))
mat
# col1 col2
# row1 "2" "4"
# row2 "3" "5"
关于在应用 apply
、sapply
等
下面举例:
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)
提前致谢:-)
我们可以将您的应用程序包装在用户定义的函数中。
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
如果您使用 []
重新分配,名称将被保留。不幸的是,这仅在您不想创建新矩阵并且不想更改元素的 class 时才有用(例如,从本例中的字符到数字)
mat[] <- apply(mat, 2, function(x) 1 + as.numeric(paste(x)))
mat
# col1 col2
# row1 "2" "4"
# row2 "3" "5"