Working with lists in purrr
Lists are incredibly useful data structures that allow you to store and organize various types of objects, such as vectors, matrices, dataframes, and even other lists. Unlike vectors, matrices, or dataframes, lists can accommodate different data types and structures within a single object. This flexibility makes them a powerful tool for data manipulation and analysis in R.
As a result the purrr
package provides lots of functions for working with lists, and in this short recipe, we’ll look at a few for summarizing, simplifying, and extracting data.
Getting ready
We’ll just need the purrr
package.
How to do it…
We can manipulate lists in purrr
using the following functions:
- Filter a list of elements:
set.seed(2345)l <- list( a = rnorm(10, mean = 1), b = rnorm(10, mean = 10), c = rnorm(10, mean = 20))library(purrr)keep(l, function(x) mean(x) >= 10)keep(l, ~ mean(.x) >= 10)detect_index...