Follow-up to my earlier question. (Thanks to @akrun for his help.)
Want to print each data.frame
of a list into separate Tables with caption as data.frame
name and description from another object. My attempted code is given below. Not being able to get description in tables caption.
What am I missing here?
If this is working:
Names1 %>%
filter(Name == quote(df1)) %>%
pull(Desp)
Why is this not working inside imap
?
Names1 %>%
filter(Name == quote(.y)) %>%
pull(Desp)
Complete Code
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|
CodePudding user response:
.y
is already quoted within imap
as is seen by the output of the first part of paste0("Test ", .y, " ( ",
which returns Table: Test df1 (
so you don't need quote.
Note:
Names1 %>%
filter(Name == "df1") %>%
pull(Desp)
# [1] "Desp1"
so if you don't include quote it works:
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|
The way you were doing it, it was filtering for something that wasn't in the data.frame (.y
). See here:
imap(
.x = ls1
, .f = ~ {
.y
}
)
# $df1
# [1] "df1"
# $df2
# [1] "df2"
imap(
.x = ls1
, .f = ~ {
quote(.y)
}
)
# $df1
# .y
# $df2
# .y