R 将列表的每个 data.frame 打印到单独的表中,标题为 data.frame 名称和描述

R printing each data.frame of a list into separate Tables with caption as data.frame name and description

Follow-up 到我的 . (感谢@akrun 的帮助。)

想要将列表的每个 data.frame 打印到单独的表格中,标题为 data.frame 名称和来自另一个 object 的描述。我尝试的代码如下。无法在表格标题中获取描述。

我在这里错过了什么?

如果这有效:

Names1 %>% 
      filter(Name == quote(df1)) %>% 
      pull(Desp)

为什么这在 imap 中不起作用?

Names1 %>% 
 filter(Name == quote(.y)) %>% 
 pull(Desp)

完整代码

library(tidyverse)
library(kableExtra)
#> 
#> Attaching package: 'kableExtra'
#> The following object is masked from 'package:dplyr':
#> 
#>     group_rows

df1 <- data.frame(X = 1:3)
df2 <- data.frame(Y = 5:6)

ls1 <-
  list(df1, df2) %>% 
  set_names(c("df1", "df2"))

ls1
#> $df1
#>   X
#> 1 1
#> 2 2
#> 3 3
#> 
#> $df2
#>   Y
#> 1 5
#> 2 6

Names1 <- 
  tibble(
    Name = c("df1", "df2")
  , Desp = c("Desp1", "Desp2")
  )

Names1
#> # A tibble: 2 x 2
#>   Name  Desp 
#>   <chr> <chr>
#> 1 df1   Desp1
#> 2 df2   Desp2

Names1 %>% 
  filter(Name == quote(df1)) %>% 
  pull(Desp)
#> [1] "Desp1"


imap(
    .x = ls1
  , .f = ~ {
    kbl(
       x       = .x
     , format  = "markdown"
     , caption = paste0("Test ", .y, " ( ", 
                        Names1 %>% 
                          filter(Name == quote(.y)) %>% 
                          pull(Desp)
                        , " )"
                        )
    )
    }
  )
#> $df1
#> 
#> 
#> Table: Test df1 (  )
#> 
#> |  X|
#> |--:|
#> |  1|
#> |  2|
#> |  3|
#> 
#> $df2
#> 
#> 
#> Table: Test df2 (  )
#> 
#> |  Y|
#> |--:|
#> |  5|
#> |  6|

.y 已经在 imap 中被引用,正如 paste0("Test ", .y, " ( ", 第一部分的输出所见 returns Table: Test df1 ( 所以你不不需要报价。

注:

Names1 %>% 
  filter(Name == "df1") %>% 
  pull(Desp)
# [1] "Desp1"

因此,如果您不包含引号,它会起作用:

imap(
  .x = ls1
  , .f = ~ {
    kbl(
      x       = .x
      , format  = "markdown"
      , caption = paste0("Test ", .y, " ( ", 
                         Names1 %>% 
                           filter(Name == .y) %>% 
                           pull(Desp)
                         , " )"
      )
    )
  }
)
# $df1


# Table: Test df1 ( Desp1 )

# |  X|
# |--:|
# |  1|
# |  2|
# |  3|

# $df2


# Table: Test df2 ( Desp2 )

# |  Y|
# |--:|
# |  5|
# |  6|

您这样做的方式是过滤 data.frame (.y) 中不存在的内容。看这里:

imap(
  .x = ls1
  , .f = ~ {
    .y
  }
)
# $df1
# [1] "df1"

# $df2
# [1] "df2"


imap(
  .x = ls1
  , .f = ~ {
    quote(.y)
  }
)
# $df1
# .y

# $df2
# .y