How to use colnames In R Language

By using this function we can get column names. We have to iterate through for loop to get all the column names.

Syntax:

for (iterator in colnames(dataframe)){
    print(iterator )
}

where

  • dataframe is the input dataframe
  • iterator is a variable is used to iterate the elements

Example:

R




# create dataframe with 4 columns
data = data.frame(column1=c(23, 45), column2=c(50, 39),
                  column3=c(33, 45), column4=c(11, 39))
 
# display
print(data)
 
# display column names
for (i in colnames(data)){
    print(i)
}


Output:



How to Loop Through Column Names in R dataframes?

In this article, we will discuss how to loop through column names in dataframe in R Programming Language.

Similar Reads

Method 1: Using sapply()

Here we are using sapply() function with some functions to get column names. This function will return column names with some results...

Method 2: Using colnames

...

Contact Us