R 将列表中的每个“data.frame”打印到单独的表中,标题为“data.frame”名称
想要将列表的每个 data.frame
打印到单独的表格中,标题为 data.frame
名称。我尝试的代码如下。它生成表格,但标题错误。
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|
Want to print each data.frame
of a list into separate Tables with caption as data.frame
name. 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|
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
它应该是
.y
。如果它是一个命名的列表/向量
,则名称默认位于.y
中,值位于.x
中,这类似于传递map2
中的两个参数。如果没有名称,则.y
将返回list
输出的序列索引
It should be
.y
. If it is a namedlist/vector
, the names are by default in.y
and the values are in.x
which is similar to passing two arguments inmap2
. If there are no names, then the.y
will return the sequence index of thelist
-output