Search code examples
r-markdowngsubkableextraemmeans

Replace ":" with " x " in `emmeans::joint_tests` output


I bring this question over from tex exchange because it didn't get much attention there The answer I got doesn't apply to tables longer than 3 rows. Please see how I could change my code. Thanks for your attention. https://tex.stackexchange.com/questions/594324/how-to-replace-all-with-or-x-in-an-anova-table

library(emmeans)
library(kableExtra)
neuralgia.glm <- glm(Pain ~ Treatment * Sex * Age, family=binomial, data = neuralgia)

model term        df1 df2 F.ratio p.value
 Treatment           2 Inf       0 1.0000 
 Sex                 1 Inf       0 0.9964 
 Age                 1 Inf       0 0.9941 
 Treatment:Sex       2 Inf       0 1.0000 
 Treatment:Age       2 Inf       0 1.0000 
 Sex:Age             1 Inf       0 0.9942 
 Treatment:Sex:Age   2 Inf       0 1.0000 

I want to replace all the colons with x and add space for ease of view. That's what I tried with gsub(":", " x "). The print(neuralgia.glm, export = T) command keeps the p-value format as <0.0001 instead of 0 when knitted.

This code gave me just an x. Using sub or gsub do the same.

joint_tests(neuralgia.glm) %>%
  print(, export = T) %>% 
  gsub(":", " x ") %>%
  kable()

enter image description here

This code replaced the colons with " x " but it broke the table.

gsub( "\\:", " x ", print(neuralgia.glm, export = T)) %>%
  kable() 

enter image description here


Solution

  • Note the order of the arguments to gsub() has x = as the third argument, not the first. So your piping wouldn't work.

    Solution:

    library(emmeans)
    
    neuralgia.glm <- glm(Pain ~ Treatment * Sex * Age, family=binomial, data = neuralgia)
    #> Warning: glm.fit: fitted probabilities numerically 0 or 1 occurred
    
    jt <- joint_tests(neuralgia.glm)
    
    jt$`model term` <- gsub(":", " x ", jt$`model term`)
    
    jt
    #>  model term            df1 df2 F.ratio p.value
    #>  Treatment               2 Inf       0 1.0000 
    #>  Sex                     1 Inf       0 0.9970 
    #>  Age                     1 Inf       0 0.9951 
    #>  Treatment x Sex         2 Inf       0 1.0000 
    #>  Treatment x Age         2 Inf       0 1.0000 
    #>  Sex x Age               1 Inf       0 0.9952 
    #>  Treatment x Sex x Age   2 Inf       0 1.0000
    

    Created on 2021-06-07 by the reprex package (v2.0.0)