R for statistics

从单因素到多因素的自动化筛选及图表构建

2022-09-22  本文已影响0人  灵活胖子的进步之路


# 1.生存资料单因素到多因素 -----------------------------------------------------------------

library(tidyverse)
library(ezcox)
library(gtsummary)
library(survival)
library(compareGroups)

rm(list = ls()) 
options(stringsAsFactors = T)

#加载数据集
data("cancer")
df <- na.omit(colon)
colnames(colon)

#提取单因素分析结果
##构建time to event的结局变量
df$ttevent <- with(df, Surv(time, as.integer(status==1)))
##构建表格
one_table<-descrTable(ttevent~ .-time-status,
                      show.ratio =T,
                      data = df,
                      show.p.trend=F);one_table
##输出表格
export2word(one_table,file = "one_cox.docx")


#确定分析变量及生存结果变量
vars <- dput(colnames(df))


#批量单因素COX回归
one_cox <- ezcox(data = df,
                time = "time",
                status = "status",
                covariates = vars)

#提取P值小于0.05的变量名称
sigcov <- one_cox%>%
  filter(p.value<0.5)%>%
  select(Variable)%>%
  distinct(Variable)%>%
  .$Variable

#构建公式
y <- "Surv(time, status)"
forml<- as.formula(paste(y, paste(sigcov,collapse=" + "), sep=" ~ "))

#多因素COX回归分析并提取结果
multicox <-
  coxph(forml, data = df) %>%
  tbl_regression(exponentiate = TRUE) %>%
  add_global_p();multicox 


#提取多因素分析结果
multicox%>%
  as_gt() %>%
  gt::gtsave("multicox.rtf") 

# 2. 逻辑回归单因素到多因素----------------------------------------------------------------------

library(tidyverse)
library(compareGroups)
library(CBCgrps)
library(rms)


rm(list = ls()) 
options(stringsAsFactors = T)

#加载数据集
data("cancer")
df <- na.omit(colon)
colnames(colon)

#确定分析变量
vars <- dput(colnames(df))


#提取单因素分析结果

one_log <- descrTable(status~ .,
                      show.ratio =TRUE,
                      data = df,
                      show.p.ratio = T,
                      show.p.trend=F) ;one_log

export2word(one_log,file = "one_log.docx")


#筛选单因素分析有意义变量

onesig<- CBCgrps::twogrps(df = df,
                 gvar = "status",
                 varlist = vars)

#构建公式
y <- "status"
forml<- as.formula(paste(y, paste(onesig$VarExtract,collapse=" + "), sep=" ~ "))

#多因素COX回归分析并提取结果
multilog <-
  glm(forml, data = df,family = binomial) %>%
  tbl_regression(exponentiate = TRUE) %>%
  add_global_p();multilog


#提取多因素分析结果
multilog%>%
  as_gt() %>%
  gt::gtsave("multilog.rtf") 

上一篇下一篇

猜你喜欢

热点阅读