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.
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
data = data.frame (column1= c (23, 45), column2= c (50, 39),
column3= c (33, 45), column4= c (11, 39))
print (data)
print ( sapply (data, mean))
print ( sapply (data, sum))
print ( sapply (data, min))
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
data = data.frame (column1= c (23, 45), column2= c (50, 39),
column3= c (33, 45), column4= c (11, 39))
print (data)
for (i in colnames (data)){
print (i)
}
|
Output:
Last Updated :
12 Dec, 2022
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...