Loop Functions In R Programming
In this tutorial, we going to learn the loop function, in another saying we going to learn apply,lapply,tapply, and mapply if you don’t know data types, you can read Data Types In R.
What Are Loop Functions?
You can operate on data types with the loop functions, these functions save you from creating a loop over and over again. It is also possible to apply the operations you want to all data with loop functions.
Apply Loop Function
The apply function is used to operate on a matrix or data frame, resulting in a vector, list, or array. The syntax is simple, the first argument is matrix or data frame, the second argument is used to select a column or row, and the last argument specifies the action to be taken.
x <- matrix(1:6 , ncol = 3 , nrow = 2)
apply(x , 1 , sum)
In here, we have gathered up the rows of the matrix. If we are going to operate on the columns, it is sufficient to write 2 instead of 1.
Lapply Loop Function
The lapply function is used to operate on a list, the output is the same length as the input. Each element is the result of applying the operation to the corresponding element of the list.
x <- list(c(1 , 2 , 3) , c(4 , 5 , 6) , c(7 , 8 , 9)
lapply(x , mean)
very similar to the apply syntax, a list is given to the first argument and 2nd argument the action to be taken on the is written. In the example here, each index of x will be averaged and written to the same index on the output list.
Continue Read My Master Designer.