Reputation: 43
I want to put a variable in the formula argument of regression_plot_function()
function in the line
p <- purrr::map(p[1:4], ~regression_plot_function(penguins2, .x))
where I momentarily put .x
like the following.
library(palmerpenguins)
library(ggplot2)
library(purrr)
library(dplyr)
library(gridExtra)
set.seed(123)
data("penguins")
index <-
matrix(rnorm(344, 25, 20), nrow = 344, ncol = 45) %>%
as.data.frame()
penguins2 <-
penguins %>% cbind(index)
regression_plot_function <- function(dataset, i_number) {
index <- paste0("V", i_number)
dataset %>%
select(species | island | year | contains(index)) %>%
mutate(year = as.factor(year)) %>%
ggplot(aes(x = year, y = !!sym(index), color = island)) +
geom_point() +
geom_smooth(aes(group = island), method = "loess")
}
p <- list()
p <- purrr::map(p[1:4], ~regression_plot_function(penguins2, .x))
allplot_regression <- cowplot::plot_grid(plotlist = p, nrow = 2, ncol = 2)
allplot_regression
With for loops, I can write it like this
p <- list()
for (i in 1:4) {
p[[i]] <- regression_plot_function(penguins2, i_number = i)
}
But I want to try it using purrr.
Thank you!
Upvotes: 0
Views: 249
Reputation: 1298
Try replacing your loop with the following:
p <- map(1:4, ~ regression_plot_function(penguins2, i_number = .))
Upvotes: 1