How To Apply a Function to Each Column in R
The apply() function in lets you apply a given function to each column, which is useful for summarizes and aggregations.
Code used in this clip:
# Load a data set
data = mtcars
head(mtcars)
# Apply a built in function to columns
apply(X = data, # Data to apply function to
FUN = max, # Function to apply
MARGIN = 2) # Margin (axis) to apply over.
# 1 = rows, 2 = columns
# Apply a custom function to columns
my_function = function(x){
return(max(x) - min(x))
}
apply(X = data, # Data to apply function to
FUN = my_function, # Function to apply
MARGIN = 2) # Margin (axis) to apply over.
Code Clips are basic code explanations in 2 minutes or less. They are intended to be short reference guides that provide quick breakdowns and copy/paste access to code needed to accomplish common data science tasks. Think Stack Overflow with a video explanation.
* 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.
Other Videos By DataDaft
| 2019-08-05 | Introduction to R: Data Frames |
| 2019-07-15 | Introduction to R: Lists |
| 2019-07-12 | Introduction to R: Matrices |
| 2019-07-11 | Introduction to R: Vectors |
| 2019-07-10 | Introduction to R: Variables |
| 2019-07-09 | Introduction to R: Atomic Data Types |
| 2019-07-08 | Introduction to R: R Arithmetic |
| 2019-07-01 | Introduction to R: Getting Started |
| 2019-07-01 | Get the Sum of Each Row in R |
| 2019-07-01 | Get the Sum of Each Column in R |
| 2019-06-30 | How To Apply a Function to Each Column in R |
| 2019-05-22 | How to Create a Data Frame in R |
| 2019-05-22 | How to Subset a Data Frame by a Column in R |
| 2019-05-21 | How to Add a Row To a Data Frame in R |
| 2019-05-21 | How to Add Columns to a Data Frame in R |
| 2019-05-20 | How to Remove a Row From a Data Frame in R |
| 2019-05-16 | Replace NA with 0 in R |
| 2019-05-15 | Count NA in R |
| 2019-05-15 | How to Remove a Column From a Data Frame in R |
| 2019-05-14 | How to Sort a Data Frame by a Column in R |


