Open In App

How to Loop Through Column Names in R dataframes?

Improve
Improve
Like Article
Like
Save
Share
Report

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

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

Syntax:

sapply(dataframe,specific function)

where

  • dataframe is the input dataframe
  • specific function is like mean,sum,min ,max etc

Example: R program to get column names in the dataframe by performing some operations

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)
 
# get mean of all columns
print(sapply(data, mean))
 
# get sum of all columns
print(sapply(data, sum))
 
# get minimum of all columns
print(sapply(data, min))
 
# get maximum of all columns
print(sapply(data, max))


Output:

column1 column2 column3 column4
1      23      50      33      11
2      45      39      45      39
column1 column2 column3 column4 
   34.0    44.5    39.0    25.0 
column1 column2 column3 column4 
     68      89      78      50 
column1 column2 column3 column4 
     23      39      33      11 
column1 column2 column3 column4 
     45      50      45      39 

Method 2: Using colnames

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:



Last Updated : 12 Dec, 2022
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads