Open In App

Specify Multiple Arguments in apply Functions in R

Last Updated : 14 Sep, 2021
Improve
Improve
Like Article
Like
Save
Share
Report

In this article, we will discuss how to specify multiple arguments in apply functions in the R programming language.

apply() function is used to apply conditions to get the resultant data like mean of data, the sum of data, etc.

Syntax:

apply(data, margin, function, na.rm = TRUE)

where, 

  • data is the input dataframe
  • margin is used to specify the width
  • function is the function used to do some sort of computation on the data
  • na.rm is the function that check for NA values (if TRUE = removes the NA values else will not remove).

Dataframe in use:

Let us first look at how apply function can be applied to a dataframe without additional arguments.

Example: R program to use apply() without additional arguments

R




# create a dataframe with student subjects
data=data.frame(subject1=c(90,89,70,NA),
                subject2=c(100,89,98,78),
                subject3=c(NA,67,78,98))
  
# display
print(data)
  
# use apply to find mean of each subject column
apply(data, 2, mean)


Output:

Now let us pass multiple arguments to apply() function. For this na.rm is set to TRUE. It will first apply the required function on the dataframe and then remove NA values from it.

Example: R program that uses multiple arguments in apply function

R




# create a dataframe with student subjects
data=data.frame(subject1=c(90,89,70,NA),
                subject2=c(100,89,98,78),
                subject3=c(NA,67,78,98))
  
# display
print(data)
  
# use apply to get mean of each subjects
apply(data, 2, mean,na.rm=TRUE)


Output:

Example: R program to get sum of each subject column by specifying multiple arguments in apply

R




# create a dataframe with student subjects
data=data.frame(subject1=c(90,89,70,NA),
                subject2=c(100,89,98,78),
                subject3=c(NA,67,78,98))
  
# display
print(data)
  
# use apply to get sum of each subjects
apply(data, 2, sum,na.rm=TRUE)


Output:

Example: R program to get minimum and maximum of each subject by specifying multiple arguments

R




# create a dataframe with student subjects
data=data.frame(subject1=c(90,89,70,NA),
                subject2=c(100,89,98,78),
                subject3=c(NA,67,78,98))
  
# display
print(data)
  
print("=============Minimum marks============")
  
# use apply to get minimum marks of each subjects
apply(data, 2, min,na.rm=TRUE
  
print("=============Maximum marks============")
  
# use apply to get maximum marks of each subjects
apply(data, 2, max,na.rm=TRUE)


Output:



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads