Hello,
I have a plotting function that takes as arguments a tibble of data and a specific value of a grouping variable from a column within the tibble. When called, it filters the tibble by the specific value of the grouping variable and then plots some data. It works fine when called individually but I'd like to loop over all the unique values of the grouping variable to create a set of individual plots. I cannot get the function to make plots when called in the for loop. Reprex below (my real problem is a lot more complicated so I can't, for example, use facets instead of the for loop):
library(tidyverse)
#make dataset
dataset_tbl <- tibble(grouping_var = factor(c(rep("cat", 3), rep("dog", 3), rep("bird",3)))) %>%
mutate(measurement = c(rnorm(3, mean = 5, sd = 2),
rnorm(3, mean = 10, sd = 2),
rnorm(3, mean = 15, sd = 2)))
#make ploting function
plotting_fct <- function(tbl, g_var){
tbl %>%
filter(grouping_var == g_var) %>%
ggplot(aes(x = grouping_var, y = measurement)) +
geom_point()
}
#test plotting function - it works
plotting_fct(tbl = dataset_tbl, g_var = "cat")
#make a list to loop over
list_vec <- dataset_tbl %>% distinct(grouping_var)
#test plotting function on a single subset item of list - it works
plotting_fct(tbl = dataset_tbl, g_var = list_vec$grouping_var[1])
#try to print out 3 plots using for loop - doesn't work
for (i in 1:3){
plotting_fct(tbl = dataset_tbl, g_var = list_vec$grouping_var[i])
}
Thank you for your help!