Search code examples
rtibble

Convert double vector to single comma separated vector


I have a tibble:

example <-  tibble(Level = list(0.80,0.90)) %>%

                mutate(bounds = list(c(2.3,4.5),
                                     c(2.7,5.2)))

When I make a gt table, I get a 2x2 tibble that looks something like this:

Level  Bounds
0.80   2.3, 4.5
0.90   2.7, 5.1

What I want is a 2x2 gt table that has only one element under bounds, in parenthesis:

Level  Bounds
0.80   (2.3,4.5)
0.90   (2.7,5.1)

Is there a way to do this?


Solution

  • One dplyr and purrr possibility could be:

    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)
    

    If in fact two columns are needed:

    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)