Home > Blockchain >  Rename levels of a factor in tbl_regression
Rename levels of a factor in tbl_regression

Time:01-28

I would like to rename the levels of a factor within tbl_regression without changing my dataframe. I understand how to rename variable names within tbl_regression using label, but is it possible to use label to also edit factor levels?

library(tidyverse)
library(gtsummary)
glm(response ~ trt   factor(death), data = trial) %>%
  tbl_regression(
    label = list(
      trt ~ "Drug B vs A",
      `factor(death)` ~ "Death" ) <- # how to change 0/1 to alive/dead?
    )

Outcome:

         Characteristic     Beta       95% CI      p-value  
         ─────────────────────────────────────────────────────
           Drug B vs A                                                                                     
             Drug A               —          —                  
             Drug B             0.06    -0.07, 0.19      0.4    
           Death                                              
             0                    —          —                  
             1                  -0.21   -0.34, -0.08    0.002   
         ─────────────────────────────────────────────────────
           CI = Confidence Interval 

Desired outcome:

         Characteristic     Beta       95% CI      p-value  
         ─────────────────────────────────────────────────────
           Drug B vs A                                                                                     
             Drug A               —          —                  
             Drug B             0.06    -0.07, 0.19      0.4    
           Death                                              
             Alive                —          —                  
             Dead              -0.21   -0.34, -0.08    0.002   
         ─────────────────────────────────────────────────────
           CI = Confidence Interval 

CodePudding user response:

You can use modify_table_body() to change the labels of the levels

 glm(response ~ trt   factor(death), data = trial) %>%
  tbl_regression(
    label = list(
      trt ~ "Drug B vs A",
      `factor(death)` ~ "Death" ) 
  ) %>% 
  modify_table_body(
    ~.x %>% 
      mutate(label  = ifelse(label == "0", "Alive",
                             ifelse(label =="1", "Dead",label)))
  )

if you want to be more cautious about the labels you change you can add in another condition to the ifelse() statement:

glm(response ~ trt   factor(death), data = trial) %>%
  tbl_regression(
    label = list(
      trt ~ "Drug B vs A",
      `factor(death)` ~ "Death" ) 
  ) %>% 
  modify_table_body(
    ~.x %>% 
      mutate(label  = ifelse(label == "0" & variable == "factor(death)", "Alive",
                             ifelse(label =="1" & variable == "factor(death)", "Dead",label)))
  )
  •  Tags:  
  • Related