我有一个小标题:
example <- tibble(Level = list(0.80,0.90)) %>%
mutate(bounds = list(c(2.3,4.5),
c(2.7,5.2)))
当我制作gt表时,我得到一个2x2的小标题,看起来像这样:
Level Bounds
0.80 2.3, 4.5
0.90 2.7, 5.1
我想要的是一个2x2 gt表,在括号中只有一个元素在边界内:
Level Bounds
0.80 (2.3,4.5)
0.90 (2.7,5.1)
有没有办法做到这一点?
dplyr
和purrr
一种可能是:example %>%
transmute(Level_bounds = paste(unlist(Level),
paste0("(", map_chr(bounds, paste, collapse = ","), ")"),
sep = " - "))
Level_bounds
<chr>
1 0.8 - (2.3,4.5)
2 0.9 - (2.7,5.2)
如果实际上需要两列:
example %>% transmute(Level = unlist(Level), bounds = paste0("(", map_chr(bounds, paste, collapse = ","), ")")) Level bounds <dbl> <chr> 1 0.8 (2.3,4.5) 2 0.9 (2.7,5.2)
unnest
list
列,按“级别”分组,pastee
“元素以“界限”分组,并用sprintf
格式化library(dplyr)
library(tidyr)
example %>%
unnest %>%
group_by(new = Level) %>%
summarise(Level_Bounds = sprintf('%0.2f - (%s)',
first(Level), toString(bounds))) %>%
select(-new)
# A tibble: 2 x 1
# Level_Bounds
# <chr>
#1 0.80 - (2.3, 4.5)
#2 0.90 - (2.7, 5.2)
或使用pmap
library(purrr) example %>% transmute(Level_bounds = pmap_chr(., ~ paste0(..1, " - (", toString(..2), ")"))) # A tibble: 2 x 1 # Level_bounds # <chr> #1 0.8 - (2.3, 4.5) #2 0.9 - (2.7, 5.2)