The use of apply functions enables data scientists to make the things easier. In this tutorial, we go over apply, tapply, lapply, sapply, vapply and mapply. Find out how to use apply functions in R.
In this tutorial, we learn how to use apply functions in R. Firstly, we go over apply() function. Secondly, we learn how to use tapply() function to obtain results by groups. Thirdly, we learn how to use lapply() function to obtain results in listwise. Also, we use sapply() function to obtain results in vector. Moreover, we learn the use of vapply() function. At last, we go over mapply() function.
1) How to Use apply() Function in R
The apply() function takes data frames as an input. We can apply it by row or column. First, we find sum of the observations by row. Then, we calculate the sum of values by column.
mydata <- data.frame(x = 1:3, y = 11:13, z = 101:103)
apply(mydata, 1, sum)
## [1] 113 116 119
apply(mydata, 2, sum)
## x y z
## 6 36 306
Check Out: How to Merge Data Frames in R
2) How to Use tapply() Function in R
In this section, we go over tapply() function. This function is used to obtain the result by group. For this purpose, let’s contruct a data frame. Then, we use tapply() to obtain sum of observation for each group.
mydata <- data.frame(x = c("a","a","b","b"), y = 11:14)
tapply(mydata$y, mydata$x, sum)
## a b
## 23 27
3) How to Use lapply() Function in R
In this part, we learn how to use lapply() function. Firstly, we construct a list as an example. Then, we obtain sum of the observations in each of list object and return the result as a list.
mylist <- list(1:3, 11:13, 101:103)
lapply(mylist, sum)
## [[1]]
## [1] 6
##
## [[2]]
## [1] 36
##
## [[3]]
## [1] 306
Also Check: How to Remove Outliers from Data in R
4) How to Use sapply() Function in R
In this section, we use sapply() function. First, we construct a list as an example. Then, we obtain sum of the observations in each of list object and return the result as a vector.
mylist <- list(1:3, 11:13, 101:103)
sapply(mylist, sum)
## [1] 6 36 306
Also Check: How to Find Class of Each Column in R Data Frame
5) How to Use vapply() Function in R
The vapply() function is similar tı sapply() function, but vapply() function requires the output type. In our example, we return the result as numeric.
mylist <- list(1:3, 11:13, 101:103)
vapply(mylist, sum, numeric(1))
## [1] 6 36 306
6) How to Use mapply() Function in R
The mapply() requires a function and inputs. We construct a data frame. We need to have a function or we can use available function in R. Then, we can use mapply() function in which we put our function and inputs, respectively.
mydata <- data.frame(x = 1:3, y = 11:13, z = 101:103)
myfunction <- function(x, y, z){x+y+z}
mapply(myfunction, mydata$x, mydata$y, mydata$z)
## [1] 113 116 119
The application of the codes is available in our youtube channel below.
Don’t forget to check: How to Convert All Columns of Data Frame to Numeric in R
0 Comments
1 Pingback