7.5 Apply (in base R)

apply family of functions

7.5.1 lapply

lapply(f_values, f_c)
## [[1]]
## [1] -17.77778
## 
## [[2]]
## [1] 0
## 
## [[3]]
## [1] 100
## 
## [[4]]
## [1] -40

7.5.2 sapply

sapply(f_values, f_c)
## [1] -17.77778   0.00000 100.00000 -40.00000

7.5.3 vapply

vapply(f_values, f_c, numeric(1))
## [1] -17.77778   0.00000 100.00000 -40.00000

7.5.4 mapply

v1 <- c(1, 2, 3, 4)
v2 <- c(100, 200, 300, 400)
my_mean <- function(x, y){
    return((x + y) / 2)
}
# sapply(v1, v2, my_mean)
mapply(my_mean, v1, v2)
## [1]  50.5 101.0 151.5 202.0
# this is the same as purrr::map2

7.5.5 apply (2-dimensions)

apply(mtcars, MARGIN = 1, mean)
##           Mazda RX4       Mazda RX4 Wag          Datsun 710      Hornet 4 Drive 
##            29.90727            29.98136            23.59818            38.73955 
##   Hornet Sportabout             Valiant          Duster 360           Merc 240D 
##            53.66455            35.04909            59.72000            24.63455 
##            Merc 230            Merc 280           Merc 280C          Merc 450SE 
##            27.23364            31.86000            31.78727            46.43091 
##          Merc 450SL         Merc 450SLC  Cadillac Fleetwood Lincoln Continental 
##            46.50000            46.35000            66.23273            66.05855 
##   Chrysler Imperial            Fiat 128         Honda Civic      Toyota Corolla 
##            65.97227            19.44091            17.74227            18.81409 
##       Toyota Corona    Dodge Challenger         AMC Javelin          Camaro Z28 
##            24.88864            47.24091            46.00773            58.75273 
##    Pontiac Firebird           Fiat X1-9       Porsche 914-2        Lotus Europa 
##            57.37955            18.92864            24.77909            24.88027 
##      Ford Pantera L        Ferrari Dino       Maserati Bora          Volvo 142E 
##            60.97182            34.50818            63.15545            26.26273
apply(mtcars, MARGIN = 2, mean)
##        mpg        cyl       disp         hp       drat         wt       qsec 
##  20.090625   6.187500 230.721875 146.687500   3.596563   3.217250  17.848750 
##         vs         am       gear       carb 
##   0.437500   0.406250   3.687500   2.812500