How To Use Apply in R

How To Use Apply in R

Channel:
Subscribers:
53,300
Published on ● Video Link: https://www.youtube.com/watch?v=5lJX4IgmqRA



Category:
Tutorial
Duration: 4:38
4,151 views
79


The apply function lets you execute another function across a given dimension of a multidimensional data object like a data frame, matrix or array. It provides a quick way to run a function on every column or every row of a data frame, without having to write a custom for loop.

Code used in this code clip:

# Apply a function across the columns of a data frame

apply(X = mtcars, # data object
FUN = median, # function to apply
MARGIN = 2) # axis to apply to. 1 = rows, 2 = columns



# Apply a function across the rows of a data frame

stat_readout <- function(x){
return(paste(x["cyl"], "cylindar car with",
x["mpg"], "mpg, weighing", x["wt"] * 1000, "pounds."))
}

apply(X = mtcars, # data object
FUN = stat_readout, # function to apply
MARGIN = 1) # axis to apply to. 1 = rows, 2 = columns



# Function with additional arguments
stat_readout_custom <- function(x, args){
readout <- paste(x["cyl"], "cylindar car with")
for (stat in args){
readout <- paste(readout, "and", x[stat], stat)
}
return(readout)
}

apply(X = mtcars, # data object
FUN = stat_readout_custom, # function to apply
MARGIN = 1, # axis to apply to
args = c("mpg", "wt")) # additional arguments





* Note: YouTube does not allow greater than or less than symbols in the text description, so the code above will not be exactly the same as the code shown in the video! For R that means I may use = for assignment and the special Unicode large < and > symbols in place of the standard sized ones for dplyr pipes and comparisons. These special symbols should work as expected for R code on Windows, but may need to be replaced with standard greater than and less than symbols for other operating systems.







Tags:
apply in r
apply function r
r apply function
r apply
r apply family
r programming
learn r
r basics
r tutorial
apply a function to each column
apply a function to each row
apply a function to a data frame
summarize rows
summarize columns
how to apply a function in r
apply()
apply() in r
r apply() function
r apply()
apply() function in r
how to use apply in r
how to use apply() in r
apply a function in r
use apply in r