提问人:Jackie 提问时间:11/17/2023 更新时间:11/17/2023 访问量:19
如何在R中更改矩阵的列/行的名称?
How to change the names of the column/row of the matrix in R?
问:
adj_estimate <- matrix(0, nrow = 5, ncol = 5)
min_column
[1] "V1"
我希望矩阵的第一行和第一列的名称为 V1。min_column来自我之前的代码行。基本上,这是一个迭代过程。我将在每个步骤后更新列和行的名称。
我尝试
colnames(adj_estimate)[1] <- min_column
Error in dimnames(x) <- dn :
length of 'dimnames' [2] not equal to array extent
如何修复此错误?
答:
2赞
tcash21
11/17/2023
#1
矩阵没有列名或行名,因为它们都是 。NULL
> adj_estimate <- matrix(0, nrow = 5, ncol = 5)
> colnames(adj_estimate)
NULL
可以使用 传递一组初始名称。dimnames
adj_estimate <- matrix(0, nrow = 5, ncol = 5, dimnames = list(1:5, 1:5))
从那里,您可以修改名称。
colnames(adj_estimate)[1] <- 'V1.min_column'
评论
colnames(adj_estimate)
返回。不能只命名第一列。这有效:行名也是如此:有效。NULL
colnames(adj_estimate) <- c("min_column", paste0("non_min_colum", 1L:4L)).
rownames(adj_estimate) <- paste0("V", 1L:5L)