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"

I want the name of the first row and first column of the matrix to be V1. min_column is from my previous lines of codes. Basically this is an iterative process. I will update the name of column and rows after each step.

I try

colnames(adj_estimate)[1] <- min_column
Error in dimnames(x) <- dn : 
  length of 'dimnames' [2] not equal to array extent

How to fix this error?

I don't think you can name just a single row or column. To name all the rows and columns, pass a list of character vectors to dimnames().

adj_estimate <- matrix(0, nrow = 5, ncol = 5)
adj_estimate
#>      [,1] [,2] [,3] [,4] [,5]
#> [1,]    0    0    0    0    0
#> [2,]    0    0    0    0    0
#> [3,]    0    0    0    0    0
#> [4,]    0    0    0    0    0
#> [5,]    0    0    0    0    0
min_column = "V1"
dimnames(adj_estimate) <- list(c(min_column, "B","C","D","E"), c(min_column,"Z","Y","X","W"))
adj_estimate
#>    V1 Z Y X W
#> V1  0 0 0 0 0
#> B   0 0 0 0 0
#> C   0 0 0 0 0
#> D   0 0 0 0 0
#> E   0 0 0 0 0

Created on 2023-11-16 with reprex v2.0.2

Why do you want to change the row and column names? There might be a simpler solution to your problem.

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.