Joshua Rosenberg
Joshua Rosenberg

Reputation: 4226

Add column name to the column of a matrix

I am trying to add a column name to the column of a 10 column by 100 row matrix, test_matrix, which has each of its columns filled with 100 random numbers generated from runif()

test_matrix <- matrix(ncol = 10, nrow = 100)

for (i in 1:ncol(test_matrix)){
    test_matrix[, i] <- runif(100)
    colnames(test_matrix)[i] <- paste0("Column ", i)
}

I get this error:

Error in `colnames<-`(`*tmp*`, value = "Column 1") : 
length of 'dimnames' [2] not equal to array extent

Why does this not work?

Upvotes: 1

Views: 2506

Answers (1)

mlegge
mlegge

Reputation: 6913

test_matrix <- matrix(ncol = 10, nrow = 100)

colnames(test_matrix) <- paste0("Column", seq(ncol(test_matrix)))

> head(test_matrix)
       Column1 Column2 Column3 Column4 Column5 Column6 Column7 Column8 Column9 Column10
  [1,]      NA      NA      NA      NA      NA      NA      NA      NA      NA       NA
  [2,]      NA      NA      NA      NA      NA      NA      NA      NA      NA       NA
  [3,]      NA      NA      NA      NA      NA      NA      NA      NA      NA       NA
  [4,]      NA      NA      NA      NA      NA      NA      NA      NA      NA       NA
  [5,]      NA      NA      NA      NA      NA      NA      NA      NA      NA       NA
  [6,]      NA      NA      NA      NA      NA      NA      NA      NA      NA       NA

Upvotes: 2

Related Questions