将双向量转换为单逗号分隔的向量

问题描述 投票:1回答:2

我有一个小标题:

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)

有没有办法做到这一点?

r tibble
2个回答
0
投票
dplyrpurrr一种可能是:

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)


0
投票
我们可以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)

© www.soinside.com 2019 - 2024. All rights reserved.