简体   繁体   English

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

[英]R printing each `data.frame` of a list into separate Tables with caption as `data.frame` name

Want to print each data.frame of a list into separate Tables with caption as data.frame name.想要将列表的每个data.frame打印到单独的表中,标题为data.frame名称。 My attempted code is given below.我尝试的代码如下。 It produces Tables but with wrong captions.它生成表格但标题错误。

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

str(ls1)
#> List of 2
#>  $ df1:'data.frame': 3 obs. of  1 variable:
#>   ..$ X: int [1:3] 1 2 3
#>  $ df2:'data.frame': 2 obs. of  1 variable:
#>   ..$ Y: int [1:2] 5 6
names(ls1)
#> [1] "df1" "df2"

imap(
    .x = ls1
  , .f = ~ {
    kbl(
       x       = .x
     , format  = "markdown"
     , caption = names(.x)
    )
  }
)
#> $df1
#> 
#> 
#> Table: X
#> 
#> |  X|
#> |--:|
#> |  1|
#> |  2|
#> |  3|
#> 
#> $df2
#> 
#> 
#> Table: Y
#> 
#> |  Y|
#> |--:|
#> |  5|
#> |  6|

It should be .y .它应该是.y If it is a named list/vector , the names are by default in .y and the values are in .x which is similar to passing two arguments in map2 .如果它是一个命名list/vector ,名称默认在.y中,值在.x中,这类似于在map2中传递两个 arguments。 If there are no names, then the .y will return the sequence index of the list如果没有名称,则.y将返回list的序列索引

purrr::imap(
  .x = ls1
  , .f = ~ {
    kbl(
      x       = .x
      , format  = "markdown"
      , caption =.y
    )
  }
)  

-output -输出

$df1


Table: df1

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

$df2


Table: df2

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM