如何在 purrr::map() "list or atomic vector" 参数的参数中引用变量索引?

How to refer a variable index inside an argument of purrr::map() "list or atomic vector" argument?

我想在行中 regression_plot_function() 函数的公式参数中放置一个变量 p <- purrr::map(p[1:4], ~regression_plot_function(penguins2, .x)) 我暂时把 .x 放在下面的地方。

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

有了for循环,我可以这样写

p <- list()
for (i in 1:4) {
p[[i]] <- regression_plot_function(penguins2, i_number = i)
}

但我想用 purrr 试试。

谢谢!

尝试用以下内容替换您的循环:

p <- map(1:4, ~ regression_plot_function(penguins2, i_number = .))