Remove auto-generated prefixes from `pivot_longer` output

Viewed 58

How do I remove the (Intercept)_ and (carat)_ prefixes in my table? That way, I could shrink my table's width a little bit and remove name redundancy.

Using names_prefix = "" in pivot_longer() or pivot_wider() or both, similar to pivot_longer issue from tidyr documentation doesn't help.

enter image description here

The code to make the table is

library(emmeans)
library(tidyverse)
library(broom)
library(kableExtra)


models_ci <- diamonds %>% group_by(cut, color) %>% 
           do(data.frame(tidy(lm(price ~ carat, data = .), conf.int=T )))

models_ci[,1:5] %>% 
  pivot_longer(cols=c(estimate, std.error), names_prefix = "") %>% 
 pivot_wider(names_from = c(term, name), 
             values_from = value) %>%
  kbl(booktabs = T,
          linesep = "",
          digits = 2,
    caption = "95% confidence intervals") %>%
  add_header_above(c("Effects" = 2 , "Intercept" = 2, "Slope" = 2)) %>% 
  kable_styling(latex_options = c("repeat_header"))

Thank you in advance!

2 Answers

You could use setNames wtih gsub

setNames(gsub('\\(Intercept)_', "", colnames(.)))

setNames(gsub('\\carat_', "", colnames(.)))

library(emmeans)
library(tidyverse)
library(broom)
library(kableExtra)

models_ci <- diamonds %>% group_by(cut, color) %>% 
  do(data.frame(tidy(lm(price ~ carat, data = .), conf.int=T )))

models_ci[,1:5] %>% 
  pivot_longer(cols=c(estimate, std.error), names_prefix = "") %>% 
  pivot_wider(names_from = c(term, name), 
              values_from = value) %>%
  setNames(gsub('\\(Intercept)_', "", colnames(.))) %>% 
  setNames(gsub('\\carat_', "", colnames(.))) %>% 
  kbl(booktabs = T,
      linesep = "",
      digits = 2,
      caption = "95% confidence intervals") %>%
  add_header_above(c("Effects" = 2 , "Intercept" = 2, "Slope" = 2)) %>% 
  kable_styling(latex_options = c("repeat_header"))

enter image description here

One solution with colnames<-:

library(tidyverse)
library(broom)
library(kableExtra)


models_ci <- diamonds %>% group_by(cut, color) %>% 
  do(data.frame(tidy(lm(price ~ carat, data = .), conf.int=T )))

models_ci[,1:5] %>% 
  pivot_longer(cols=c(estimate, std.error)) %>% 
  pivot_wider(names_from = c(term, name), 
              values_from = value) %>%
  `colnames<-`(c("cut", "color", "estimate", "std.error", "estimate", "std.error")) %>%
  kbl(booktabs = T,
      linesep = "",
      digits = 2,
      caption = "95% confidence intervals") %>%
  add_header_above(c("Effects" = 2 , "Intercept" = 2, "Slope" = 2)) %>% 
  kable_styling(latex_options = c("repeat_header"))

-output

enter image description here

Related