Search code examples
r

Changing column names of a matrix in R without using colnames()


im new to R and was wondering if there is a way to assign names to columns in a matrix without using the colnames() function

#creating two vectors 
player <- c(rep('dark',5),rep('light',5))
piece <-c('king','queen','pawn','pawn','knight','bishop','king','rook','pawn','pawn')

#creating a matrix
matrix2 <- c(player, piece)
dim(matrix2) <- c(10, 2)

#this would work perfectly but i was looking for an alternate method which doesn't uses 
#colnames() function
colnames(matrix2) <- c('player','piece')

I also know that using cbind() would give me a matrix with column names as those of the two vectors

matrix2<-cbind(player,piece)

But I don't want to create my matrix with the cbind() function. I wanted to know if there is a way to name the colunmns of the matrix other than using the colnames() function after creating the matrix like I have created above.


Solution

  • Difficult to answer. Do you mean like this?

    dimnames(matrix2) <- list(c(1:10), c("player", "piece"))
    
    

    EDIT, without "naming" row_names (see comments, @akrun mentioned that earlier):

    dimnames(matrix2) <- list(NULL, c("player", "piece"))