Working with Lists

code
rtip
lists
lapply
Author

Steven P. Sanderson II, MPH

Published

November 29, 2022

Introduction

In R there are many times where we will work with lists. I won’t go into why lists are great or really the structure of a list but rather simply working with them.

Example

First let’s make a list.

l <- list(
  letters,
  1:26,
  rnorm(26)
)

l
[[1]]
 [1] "a" "b" "c" "d" "e" "f" "g" "h" "i" "j" "k" "l" "m" "n" "o" "p" "q" "r" "s"
[20] "t" "u" "v" "w" "x" "y" "z"

[[2]]
 [1]  1  2  3  4  5  6  7  8  9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
[26] 26

[[3]]
 [1] -1.5647537840 -1.3080486753  1.3331315389 -0.5490502644 -0.4467608750
 [6] -1.5876952894  0.2292049732 -0.2885449316  1.4614499298 -0.0864987690
[11]  0.5686850031 -0.3897819578  0.1776603862 -1.1326372302 -1.8651290164
[16]  1.2676006036  0.2405115523 -1.0506728047  1.4069277686 -1.0125778892
[21] -0.7687818102 -0.1325350681  0.3639485041  0.0005700058 -1.0698214370
[26]  1.1972767040

Now let’s look at somethings we can do with lists. First, let’s see if we can get the class of each item in the list. We are going to use lapply() for this.

lapply(l, class)
[[1]]
[1] "character"

[[2]]
[1] "integer"

[[3]]
[1] "numeric"

Now, let’s perform some simple operations on each item of the list.

lapply(l, length)
[[1]]
[1] 26

[[2]]
[1] 26

[[3]]
[1] 26
try(lapply(l, sum))
Error in FUN(X[[i]], ...) : invalid 'type' (character) of argument

Ok so we see taking the sum of the first element of the list in lapply() did not work because of a class type mismatch. Let’s see how we can get around this an only apply the sum function to a numeric type. To do this we can rely on {purrr} by using a function map_if()

library(purrr)

map_if(l, is.numeric, sum)
[[1]]
 [1] "a" "b" "c" "d" "e" "f" "g" "h" "i" "j" "k" "l" "m" "n" "o" "p" "q" "r" "s"
[20] "t" "u" "v" "w" "x" "y" "z"

[[2]]
[1] 351

[[3]]
[1] -5.006323
map_if(l, is.numeric, mean)
[[1]]
 [1] "a" "b" "c" "d" "e" "f" "g" "h" "i" "j" "k" "l" "m" "n" "o" "p" "q" "r" "s"
[20] "t" "u" "v" "w" "x" "y" "z"

[[2]]
[1] 13.5

[[3]]
[1] -0.1925509

Voila!