sapply() function
The sapply() function helps us in applying functions on a list, vector, or data frame and returns an array or matrix object of the same length. The sapply() function in the R Language takes a list, vector, or data frame as input and gives output in the form of an array or matrix object. Since the sapply() function applies a certain operation to all the elements of the object it doesn’t need a MARGIN. It is the same as lapply() with the only difference being the type of return object.
Syntax: sapply( x, fun )
Parameters:
- x: determines the input vector or an object.
- fun: determines the function that is to be applied to input data.
Example:
Here, is a basic example showcasing the use of the sapply() function to a vector.
R
# create sample data sample_data<- data.frame ( x= c (1,2,3,4,5,6), y= c (3,2,4,2,34,5)) print ( "original data:" ) sample_data # apply sapply() function print ( "data after sapply():" ) sapply (sample_data, max) |
Output:
apply(), lapply(), sapply(), and tapply() in R
In this article, we will learn about the apply(), lapply(), sapply(), and tapply() functions in the R Programming Language.
The apply() collection is a part of R essential package. This family of functions helps us to apply a certain function to a certain data frame, list, or vector and return the result as a list or vector depending on the function we use. There are these following four types of function in apply() function family:
Contact Us