2

map我正在尝试创建一系列表,并希望使用函数遍历因子变量。我能够做到这一点,但是当我想使用迭代变量作为每个表的标题时遇到了麻烦。索引和迭代是我仍在纠结的事情,所以如果有人能在下面的代码中指出我做错了什么,我将不胜感激:

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(.)
        )
      )
    )

这就是我希望为每个具有适当标题的池塘提供的输出

图像

4

2 回答 2

1

我猜你的代码的问题是你试图映射两个需要map2. 祝你好运!

Ponds_split <- Ponds %>%
  split(.$Pond) 

map2(
  Ponds_split,
  names(Ponds_split),
  ~gt(.) %>%
    tab_header(
      title = .y
      )
)

在此处输入图像描述

于 2020-11-25T08:49:14.443 回答
1

这是一个基本方法:

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

这是一种使用的巧妙方法,我们实际上返回gt对象,以便以后调用它们。

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] 

唯一的区别是,在这种 [data.table] 方法中,表中没有 Pond 列。

于 2020-11-25T12:50:54.740 回答