Search code examples
rplotpurrrgam

Get the name of iteration in purrr::map function


I am making graphs from 4 statistical models subsetting "virus" variable. I don't know how to put the title of the graphs according to "virus" variable.

I made this reproducible set:

library(dplyr)
library(tidyr)
library(lubridate)
library(mgcv)
library(purrr)


set.limpio <- data.frame(Codigo= 1:1000, Dia = rnorm(1000,100,2),
                     R = rbinom(1000,1,.5),
                    virus = c(rep("V1",250),
                              rep("V2",250),
                              rep("V3",250),
                              rep("V4",250)))
plots <- set.limpio %>% 
  filter(.$Dia < 250) %>%
  split(.$virus) %>%
  map(~ gam(R ~ s(Dia) + s(Codigo, bs = "re"), data = ., 
            family = binomial(link = "logit"), method = "REML")) %>% 
  map( ~ plot.gam(.,shade = T, scale = 0, scheme = 3,
                  xlab = "Days",
                  ylab = "Positivity"))

In this section should be the title

map( ~ plot.gam(.,shade = T, scale = 0,scheme = 3,xlab = "Days", ylab = 
    "Positivity", main = "here should be the title"))

I tried:

main = paste(names(.)) 

also with

deparse(substitute(obj))

But none of them worked.

This is how I want the graphs. That should be the result of the first graph out of the four remaining. enter image description here


Solution

  • As markus commented, you can use imap.

    plots <- set.limpio %>% 
      filter(.$Dia < 250) %>%
     split(.$virus) %>%
      map(~ gam(R ~ s(Dia) + s(Codigo, bs="re"), data = ., 
              family = binomial(link = "logit"), method="REML")) %>% 
      imap( ~ plot.gam(.,shade = T, scale = 0,scheme = 3,xlab = "Days", ylab = 
    "Positivity", main= .y))
    

    I just replaced the second map call with imap and added parameter main = .y

    If the goal is just to display plots (plot.gam doesn't return plot objects), then you should use iwalk instead and you have no need to assign it to plots to make it silent.

    see ?imap