简体   繁体   English

R:重命名矩阵的列/行的省时方法

[英]R: Time Efficient Way of Renaming Columns/Rows of a Matrix

Is there a more efficient way of doing this: The matrix expr is 15745 x 41 有没有更有效的方法:矩阵expr为15745 x 41

for (i in 1:ncol(expr)){
   colnames(expr)[i] <- paste0("V",i);
}
for (i in 1:nrow(expr)){
   rownames(expr)[i] <- paste0(i);
}
colnames(expr) <- paste0("V",1:ncol(expr))
rownames(expr) <- 1:nrow(expr)

We can use dimnames to do this 我们可以使用dimnames来做到这一点

dimnames(expr) <- list(seq_len(nrow(expr)), paste0("V", seq_len(ncol(expr))))

Or this can be also done with explicitly assigning colnames and rownames as we have commented earlier 或者,这可以明确地分配也做colnamesrownames正如我们在前面的评论

colnames(expr) <- paste0("V", seq_len(ncol(expr)))
rownames(expr) <- seq_len(nrow(expr))

Or another option is to convert it to data.frame which will automatically do the naming (if working with data.frame is okay) 或另一种选择是将其转换为data.frame ,这将自动进行命名(如果可以使用data.frame的话)

as.data.frame(expr)

data 数据

set.seed(24)
expr <- matrix(rnorm(10*5), 10, 5) 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM