Charlie Mintz
Charlie Mintz

Reputation: 79

A function to create multiple plots by subsets of data frame

I have a dataframe (NBA_Data) that is 27,538 by 29. One of the columns is called "month", and there are eight months (October:June). I would like to write a function that automatically subsets this data frame by month and then creates 8 plot-objects in ggplot2. I'm getting out of my depth here, but I imagine that these would be stored in a single list ("My Plots").

I plan to use geom_plot for each plot object to plot Points against Minutes.Played. I'm not familiar with grid.arrange, but I'm guessing that once I have "My Plots", I could use that (in some form) as an argument for grid.arrange.

I've tried:

empty_list <- list()
    for (cat in unique(NBA_Data$month)){
      d <- subset(NBA_Data, month == cat)
    empty_list <- c(empty_list, d) 
    }

This gives an unbroken list that repeats all 29 columns for each month, with a length of 261. Not ideal, but workable maybe. Then I try using lapply to split the list, but I screw it up.

lapply(empty_list, split(empty_list, empty_list$month))

Error in match.fun(FUN) : 
'split(x = empty_list, f = empty_list$month)' is not a function, character or symbol
In addition: Warning message:
In split.default(x = empty_list, f = empty_list$month) :
data length is not a multiple of split variable

Any suggestions? Thank you.

Upvotes: 2

Views: 1593

Answers (1)

Se&#241;or O
Se&#241;or O

Reputation: 17432

You can use split to chunk the dataset into a list already:

list <- split(data, data$month)

Also you can use facet_wrap to make multiple plots on one page with the same data if you're using ggplot.

library(ggplot2)
ggplot(data, aes(x = PlayerName, y = PPG)) + geom_point() + facet_wrap(~month)

Upvotes: 2

Related Questions