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 #rename column names of matrix colnames(new_matrix) new_vec1', 'new_vec2')
Method 2: Rename Columns During cbind
#cbind two vectors into matrix and rename columns
new_matrix
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 #cbind the two vectors into a matrix new_matrix #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) 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 #cbind two vectors into matrix and rename columns new_matrix #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)