Search code examples
rloopsdictionarygt

How to iterate through an object with map in R to create a series of gt tables


I am trying to create a series of tables and want to iterate through a factor variable using map function. I am able to do that, but am running into trouble when I want to use the iterated variable as a title for each table. Indexing and iterating is something I am still wrapping my head around, so I would appreciate it if anyone could point out what I am doing wrong in the code below:

library(gt)
Area1 <- as.factor(c(0,0, 0.50659782, "NS"))
Area2 <- c(NA, NA, 0.507, NA)
Pond  <- c('MGF', '101W', 5, 5)
Ponds <-data.frame(Area1, Area2, Pond)

Ponds %>%
    split(.$Pond) %>% 
    map(~gt(.) %>%
      tab_header(
        title = map(., names(.)
        )
      )
    )

This is what I would like to have as output for each pond with the appropriate title

img


Solution

  • I guess the problem with your code is that you are trying to map over two objects which requires map2. Good luck!

    Ponds_split <- Ponds %>%
      split(.$Pond) 
    
    map2(
      Ponds_split,
      names(Ponds_split),
      ~gt(.) %>%
        tab_header(
          title = .y
          )
    )
    

    enter image description here