Set column names using colnames() function

colnames() function in R Language is used to set the names to columns of a matrix.

Syntax:
colnames(x) <- value

Parameters:
x: Matrix
value: Vector of names to be set

Example: R program to set the column names using colnames() function.

R




# create two vectors with integer and string types
vector1 = c(1,2,3,4,5)
  
vector2 = c("sravan","bobby","ojsawi",
            "gnanesh","rohith")
  
# display
print(vector1)
print(vector2)
  
# combine two vectors using cbind()
combined = cbind(vector1,vector2)
  
# Applying colnames
colnames(combined) = c("vector 1", "vector 2")    
  
# display
combined


Output:

Set Column Names when Using cbind Function in R

In this article, we are going to see how to set the column names when using cbind() function in R Programming language.

Let’s create and combine two vectors for demonstration:

R




# create two vectors with integer and string types
vector1 = c(1,2,3,4,5)
  
vector2 = c("sravan","bobby",
            "ojsawi","gnanesh",
            "rohith")
  
# display
print(vector1)
print(vector2)
  
# combine two vectors using cbind()
print(cbind(vector1, vector2))


Output:

[1] 1 2 3 4 5
[1] "sravan"  "bobby"   "ojsawi"  "gnanesh" "rohith"  
    vector1 vector2  
[1,] "1"     "sravan"  
[2,] "2"     "bobby"  
[3,] "3"     "ojsawi"  
[4,] "4"     "gnanesh"
[5,] "5"     "rohith"

Similar Reads

Method 1 : Set column names using colnames() function

...

Method 2 : Set column names within cbind() function

colnames() function in R Language is used to set the names to columns of a matrix....