0

I have a function that takes a dataset, filters for a given element, and creates a plot. I want to take a vector and use map to filter for each element of the vector and create a plot. Applying map(vector, function) doesn't work--I get the warning

"longer object length is not a multiple of shorter object length".

Say I have this dataframe names, based on the babynames dataset.

names <- babynames%>%
  pivot_wider(names_from = sex, values_from = n, values_fill=0) %>%
  group_by(year,name) %>%
  summarize(Female=sum(F), Male=sum(M))  %>%
  mutate(percent = Female/(Male+Female)*100)

and a vector made up of `"Ollie"`, `"Verna"`, and `"Ava"`. I want a graph for each of `Ollie`, `Verna`, and `Ava`.

fun_name <- function(name_1) {
    names %>%
    filter(name==name_1) %>%
    ggplot(aes(x=year, y=percent)) +
    geom_line()
}

map(vector, fun_name)

The issue I'm specifically having now is that all of the graphs are combined into one.

eclare
  • 139
  • 5
  • Please post your example data using `dput`, as pictures of data is tiresome and unpractical to work with. – mhovd Nov 01 '20 at 14:47

1 Answers1

1

You can try :

library(tidyverse)
library(babynames)

vector <- c("Ollie", "Verna", "Ava")

fun_name <- function(name_1) {
  names %>%
    filter(name==name_1) %>%
    ggplot(aes(x=year, y=percent)) +
    geom_line()
}

plot_list <- map(vector, fun_name)
length(plot_list)
#[1] 3

The individual plots are in plot_list[[1]], plot_list[[2]] etc.

Ronak Shah
  • 377,200
  • 20
  • 156
  • 213
  • I get a single graph in this case. – eclare Nov 01 '20 at 14:20
  • `data = df` should be changed to `data = names` for your case I think. Did you check `plot_list[[1]]`, `plot_list[[2]]` etc? – Ronak Shah Nov 01 '20 at 14:22
  • plot_list[[1]] isn't found; list_plot is a list of length 1. data = names is what I used. – eclare Nov 01 '20 at 14:25
  • Ok..then can you provide a reproducible example using `dput` instead of an image to test the answer? We cannot copy data from an image. – Ronak Shah Nov 01 '20 at 14:27
  • Can you add your own data with dput()? I searched and found [this page](https://stackoverflow.com/questions/49994249/example-of-using-dput), which doesn't show any way I can. – eclare Nov 01 '20 at 14:40
  • You just need to add `dput(names)` to your post. I have updated the answer to show that the code works on the default `mtcars` dataset. Your screenshot doesn't even include column names to make sure that your columns are actually called `name`, `year` and `frequency`. Read this post to know how to share a reproducible example http://stackoverflow.com/questions/5963269 so that it is easier to help you. – Ronak Shah Nov 01 '20 at 14:45
  • I'm sorry, I'm still not understanding how dput works. names is a dataset I created by editing an existing one. – eclare Nov 01 '20 at 15:04
  • @eclare My answer works for the example that you have shared in your post. See updated answer. What does it give you? – Ronak Shah Nov 01 '20 at 15:20