Splitting a dataframe by every n unique values of a variable

Viewed 63

I have a dataframe of Lots, Time, Value with the same structure as the sample data below.

df <- tibble(Lot = c(rep(123,4),rep(265,5),rep(132,3),rep(455,4)), 
time = c(seq(4), seq(5), seq(3), seq(4)), Value = runif(16))

I'd like to split the dataframe by every N Lots and plot them. The Lots are different sizes so I can't subset the data by every n rows!

I've been using an approach like this but it's not scalable for a large dataset.

df %>% filter(Lot == c(123, 265)) %>% ggplot(., aes(x = time, y = Value)) + 
geom_point() + stat_smooth()

How can I do this?

1 Answers

Create a lot number column and create a list of plots for every n unique lot values.

This would give you list of plots.

library(tidyverse)

lot_n <- 2

df %>%
  mutate(Lot_number = match(Lot, unique(Lot)), 
         group = ceiling(Lot_number/lot_n)) %>%
  group_split(group) %>%
  map(~ggplot(.x, aes(x = time, y = Value)) + 
        geom_point() + stat_smooth()) -> list_plots

list_plots

Individual plots can be accessed via list_plots[[1]], list_plots[[2]] etc.

You can also plot the data with facets.

df %>%
  mutate(Lot_number = match(Lot, unique(Lot)), 
         group = ceiling(Lot_number/lot_n)) %>%
  ggplot(aes(x = time, y = Value)) + 
  geom_point() +  stat_smooth() + 
  facet_wrap(~group, scales = 'free')

enter image description here

Related