using sep argumnt to put double rounded parenthesis

63 views Asked by At

I would like to close in double parenthesis the second column I am trying to unite

library(tidyr)

mtcars %>% 
  summarise(mean = mean(mpg), 
            sd = sd(mpg)) %>% 
  tidyr::unite('A', 1:2, sep = ' (')

On this purpose I am using the sep argument but I do not know whether it is possible somehow or not using this method. If not could you please provide some other example?

This is the desired output

                           A
1 20.090625 (6.0269480520891)
2

There are 2 answers

8
Gregor Thomas On

I think paste, sprintf, and glue are all more natural choices than unite for this.

library(dplyr)
library(glue)
mtcars %>% 
  summarise(mean = mean(mpg), 
            sd = sd(mpg)) %>% 
  mutate(
    paste = paste0(mean, " (", sd, ")"),
    sprintf = sprintf("%s (%s)", mean, sd),
    glue = glue("{mean} ({sd})")
  )
#       mean       sd                      paste                     sprintf
# 1 20.09062 6.026948 20.090625(6.0269480520891) 20.090625 (6.0269480520891)
#                          glue
# 1 20.090625 (6.0269480520891)
0
maike On

just add the parentheses before unite

mtcars %>% 
  summarise(mean = mean(mpg), 
            sd = sd(mpg)) %>% 
  mutate(sd = paste0('(', sd, ')')) %>% 
  tidyr::unite('A', 1:2, sep = ' ')