R: How to Rename Columns When Using cbind


There are two ways to rename columns when using the cbind function in R:

Method 1: Rename Columns After Using cbind

#cbind two vectors into a matrix
new_matrix <- cbind(vec1, vec2)

#rename column names of matrix
colnames(new_matrix) <- c('new_vec1', 'new_vec2')

Method 2: Rename Columns During cbind

#cbind two vectors into matrix and rename columns
new_matrix <- cbind(new_vec1 = vec1, new_vec2 = vec2)

The following examples show how to use each method in practice.

Example 1: Rename Columns After Using cbind

The following code shows how to use cbind to bind together two vectors into a matrix and then rename the columns of the matrix afterwards:

#create two vectors
vec1 <- c(1, 3, 3, 4, 5)
vec2 <- c(7, 7, 8, 3, 2)

#cbind the two vectors into a matrix
new_matrix <- cbind(vec1, vec2)

#view matrix
new_matrix

     vec1 vec2
[1,]    1    7
[2,]    3    7
[3,]    3    8
[4,]    4    3
[5,]    5    2

#rename columns
colnames(new_matrix) <- c('new_vec1', 'new_vec2')

#view matrix
new_matrix

     new_vec1 new_vec2
[1,]        1        7
[2,]        3        7
[3,]        3        8
[4,]        4        3
[5,]        5        2

Using this method, we’re able to cbind together the two vectors into a matrix and then use the colnames() function to rename the columns of the resulting matrix.

Example 2: Rename Columns During cbind

The following code shows how to use cbind to bind together two vectors into a matrix and simultaneously rename the columns:

#create two vectors
vec1 <- c(1, 3, 3, 4, 5)
vec2 <- c(7, 7, 8, 3, 2)

#cbind two vectors into matrix and rename columns
new_matrix <- cbind(new_vec1 = vec1, new_vec2 = vec2)

#view matrix
new_matrix

     new_vec1 new_vec2
[1,]        1        7
[2,]        3        7
[3,]        3        8
[4,]        4        3
[5,]        5        2 

Using this method, we’re able to rename the columns of the resulting data frame during the cbind function.

The benefit of using this method is that we’re able to use the cbind function and rename the columns using a single line of code.

Additional Resources

The following tutorials explain how to perform other common tasks in R:

How to Use cbind in R (With Examples)
How to Use rbind in R (With Examples)

Leave a Reply

Your email address will not be published.