How to use sapply() In R 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




# 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 

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