2

I have a nested list containing 15 datasets (also lists), each of which has 3 columns but a variable number of rows (thousands each). The top of the last dataset looks like this in the console:

[[15]]
           Object.Number            Internal                      Membrane
1                0                 8.275335e+03                   2575.41042
2                2                 1.225267e+04                   5813.50000
3                3                 9.554725e+03                   2483.51172

I would like to make a 5x3 grid of density plots, created using the values in the 2nd column of each of 15 datasets.

I thought I could do this with lapply (myFiles, densityplot(args)) but I can't find a way to reference the column within the arguments for densityplot.

Would be grateful for any insights on how this can be achieved.

Olly
  • 67
  • 7

2 Answers2

2

I would use dplyr::bind_rows with argument .id to row-bind all data.frames into a single data.frame; then use ggplot2 with facet_wrap to plot densities in a 3x5 grid layout.

Here is an example using the mtcars sample data:

# Create sample data
lst <- replicate(15, mtcars, simplify = F)

# Plot
library(tidyverse)
bind_rows(lst, .id = "id") %>%
    mutate(id = factor(id, levels = as.character(1:15))) %>%
    ggplot(aes(mpg)) +
    geom_density() +
    facet_wrap(~ id, nrow = 3, ncol = 5)

enter image description here

Maurits Evers
  • 49,617
  • 4
  • 47
  • 68
1

In purrr you can use the shorthand notation using ~ and .x, for example:

library(purrr)
map(myFiles, ~ densityplot(.x[[2]]))
Vlad C.
  • 944
  • 7
  • 12
  • This is interesting. I don't know purrr at all, but I will certainly look into it. It seems like a very efficient way to do this. – Olly Sep 12 '18 at 11:47
  • Yes, the syntax using `.x` and `~` is short and convenient. It's however no different from defining the function inside `lapply` or `map`. So `map(myFiles, ~ densityplot(.x[[2]]))` is the same as `map(myFiles, function(x) densityplot(x[[2]]))`. The latter is in turn the equivalent of `lapply(myFiles, function(x) densityplot(x[[2]]))`. You can have a look at this comparison between `map` and `lapply` https://stackoverflow.com/questions/45101045/why-use-purrrmap-instead-of-lapply – Vlad C. Sep 12 '18 at 12:55