1

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!

AnilGoyal
  • 25,297
  • 4
  • 27
  • 45
hnguyen
  • 772
  • 6
  • 17

2 Answers2

2

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

TarJae
  • 72,363
  • 6
  • 19
  • 66
1

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

bttomio
  • 2,206
  • 1
  • 6
  • 17
  • 1
    Thank you. This is helpful when ones have to detail names some more, such as cap, lower case, italics,... – hnguyen Apr 15 '21 at 13:53