【问题标题】:Remove auto-generated prefixes from `pivot_longer` output从 `pivot_longer` 输出中删除自动生成的前缀
【发布时间】:2021-07-10 03:09:21
【问题描述】:

如何删除表中的 (Intercept)_(carat)_ 前缀?这样,我可以稍微缩小我的表格宽度并删除名称冗余。

pivot_longer()pivot_wider() 或两者中使用names_prefix = "",类似于pivot_longer issue from tidyr documentation 没有帮助。

制作表格的代码是

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"))

提前谢谢你!

【问题讨论】:

    标签: r r-markdown tidyverse kableextra broom


    【解决方案1】:

    您可以使用setNamesgsub

    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"))
    

    【讨论】:

      【解决方案2】:

      colnames&lt;- 的一个解决方案:

      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"))
      

      -输出

      【讨论】:

      • 谢谢。这在必须详细说明名称时很有帮助,例如大写、小写、斜体……
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-09-18
      • 1970-01-01
      • 2012-08-13
      • 2021-08-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多