Home > Software design >  Renaming columns of matrix based on pattern
Renaming columns of matrix based on pattern

Time:12-13

I'm new to R and have encountered a problem when wanting to rename my columns. This is my matrix and I want to rename each column as gene 1, gene 2 etc.

count.data <- matrix(data = 1, nrow = 3, ncol = 5)

I've seen some example of using colnames() = c() but I don't know how to apply it to my matrix. All help is appreciated!

CodePudding user response:

This is a good reason to use sprintf, which allows you to print a formatted string.

%d in the first argument is replaced by the sequence of integers in the second argument.

colnames(count.data) = sprintf("gene%d", 1:ncol(count.data))
     gene1 gene2 gene3 gene4 gene5
[1,]     1     1     1     1     1
[2,]     1     1     1     1     1
[3,]     1     1     1     1     1

CodePudding user response:

use colnames() method. Syntax: colnames(df) <-
c(new_col1_name,new_col2_name,new_col3_name). 

You can find a detailed article: https://www.geeksforgeeks.org/change-column-name-of-a-given-dataframe-in-r/

  •  Tags:  
  • r
  • Related