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

Viewed 266

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

2 Answers

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

Here is a base approach:

by(data = Ponds,
   INDICES = Ponds$Pond,
   FUN = function (x) {
     obj = gt(x)
     tab_header(data = obj, title = x$Pond[1L])
   })

And here is a neat way with in which we actually return the gt objects so we can call them later.

library(data.table)
dt = as.data.table(Ponds)
res = dt[, 
         {gt_obj = tab_header(data = gt(.SD),
                              title = .BY[[1L]])
         print(gt_obj) ##makes it display in viewer
         list(list(gt_obj))
         }
         , by = Pond]
res

##      Pond           V1
##    <char>       <list>
## 1:    MGF <gt_tbl[16]>
## 2:   101W <gt_tbl[16]>
## 3:      5 <gt_tbl[16]>

res[Pond == "MGF", V1] 

The only difference is that in this [data.table] approach, there is no Pond column in the table.

Related