How To Use Apply in R @DataDaft
How To Use Apply in R  @DataDaft
Uploaded February 2020 | Updated November 2026, 3 hours ago
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.
How To Use Apply in RPython Programming Practice: LeetCode #14   Longest Common PrefixPython Regex: How To Replace All Substrings In a StringNew Anime Popularity (2018-2020)U.S. Major Sports League Worldwide Web Search Volume (01/2004 - 10/2019)How To Add a Column to a Data Frame in Pandas (Python)How to Use **kwargs in PythonPython for Data Analysis: Plotting With PandasHow To Generate Random Numbers in RHow to Make Boxplots in RGoku vs Vegeta: Power Levels Over TimePython Programming Practice: LeetCode #20   Valid Parentheses
DataDaft |

How To Use Apply in R

SHARE TO X SHARE TO REDDIT SHARE TO FACEBOOK WALLPAPER