Learn/R Programming/Advanced R

Apply Functions

Topic: Apply

Advertisement

Introduction

The apply family provides vectorized operations. They iterate over arrays, lists, or data frames.

Apply Functions

# lapply - returns list
lapply(list, function)

# sapply - simplifies to vector
sapply(list, function)

# vapply - with type specification
vapply(list, function, numeric(1))

# apply - for matrices
apply(matrix, MARGIN, function)
# MARGIN: 1 = row, 2 = column

Specialized Applies

# mapply - multiple vectors
mapply(rep, 1:3, 3:1)

# tapply - grouped apply
tapply(data, group, function)

# rapply - recursive apply
rapply(list, function, classes = "numeric")

Example

# Column means
apply(df, 2, mean)

# Row sums
apply(df, 1, sum)

# Custom function
apply(df, 2, function(x) mean(x, na.rm = TRUE))

Summary

Apply functions replace loops for efficiency. Use the appropriate function for your data structure.

Advertisement

Advertisement

Need More Practice?

Get personalized R programming help from ChatWhole's AI-powered platform.

Get Expert Help →