Simple lapply()

code
rtip
weeklytip
Author

Steven P. Sanderson II, MPH

Published

October 5, 2022

This is a simple lapply example to start things off.

# Let l be some list of lists, where all elements of lists are numbers
l <- list(
  a = 1:10,
  b = 11:20,
  c = 21:30
)

Now let’s take a look at our list l and see it’s structure.

l
$a
 [1]  1  2  3  4  5  6  7  8  9 10

$b
 [1] 11 12 13 14 15 16 17 18 19 20

$c
 [1] 21 22 23 24 25 26 27 28 29 30

Now that we see the structure, we can use the lapply function to get the sum of each list element, the mean, etc.

lapply(l, sum)
$a
[1] 55

$b
[1] 155

$c
[1] 255
lapply(l, mean)
$a
[1] 5.5

$b
[1] 15.5

$c
[1] 25.5

Voila!