J.Se
J.Se

Reputation: 155

Renaming columns of matrix based on pattern

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!

Upvotes: 0

Views: 129

Answers (2)

Quickk Care
Quickk Care

Reputation: 51

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/

Upvotes: 1

user438383
user438383

Reputation: 6206

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

Upvotes: 1

Related Questions