Functional programming is a programming paradigm that treats computation as the evaluation of mathematical functions. In R, you can use functions like lapply
, sapply
, and map
from the purrr
package.
Step 1: Install and Load purrr
rCopy codeinstall.packages("purrr")
library(purrr)
Step 2: Create a Sample List
rCopy code# Create a list of numeric vectors
num_list <- list(a = 1:5, b = 6:10, c = 11:15)
Step 3: Use lapply and sapply
rCopy code# Apply a function to each element using lapply
squared_list <- lapply(num_list, function(x) x^2)
print(squared_list)
# Use sapply to simplify the output to a matrix
squared_matrix <- sapply(num_list, function(x) x^2)
print(squared_matrix)
Step 4: Use map from purrr
rCopy code# Use map to apply a function and return a list
squared_map <- map(num_list, ~ .x^2)
print(squared_map)
Leave a Reply