本文学习https://mp.weixin.qq.com/s/Xa-QT9L_qZI4KGozcQrYcA
1. 数据来源
> library(boot)
> head(melanoma)
time status sex age year thickness ulcer
1 10 3 1 76 1972 6.76 1
2 30 3 1 56 1968 0.65 0
3 35 2 1 41 1977 1.34 0
4 99 3 0 71 1968 2.90 0
5 185 1 1 52 1965 12.08 1
6 204 1 1 28 1971 4.84 1
2. 调整数据用于后续分析
# 2 对应alive,1 对应Melanoma death,3对应Non-melanoma death
melanoma$status_label <- factor(melanoma$status,levels=c(2,1,3),labels=c("Alive","Melanoma death","Non-melanoma death"))
# 没有标签默认小的等于第一个
melanoma$sex_label <- factor(melanoma$sex,labels=c("Male","Female"))
melanoma$ulcer_label <- factor(melanoma$ulcer,labels=c("Present","Absent"))
3. 定义一个函数
library(Rcpp)
library(htmlTable)
library(Gmisc)
getT1Stat <- function(varname,digits=1){
getDescriptionStatsBy(melanoma[,varname],
melanoma$status_lable,
add_total_col = TRUE,
show_all_values = TRUE,
hrzl_prop = FALSE,
useNA="ifany",
statistics=TRUE,
statistics.sig_lim = 10^-3,
html=TRUE,
digits=digits
)
}
image.png
- 函数定义完成后,建立一个空的列表,以储存每个变量的分析结果,并进行分析,将结果储存在列表中:
table_data <- list()
table_data[["Sex"]] <- getT1Stat("sex_label")
table_data[["Age"]] <- getT1Stat("age")
table_data[["Ulceration"]] <- getT1Stat("ulcer_label")
table_data[["Thickness<sup>a</sup>"]] <- getT1Stat("thickness",2)
- 将所有结果merge到一个矩阵中,并建立rgroup(table1第一列的变量名) 和 n.rgroup(table 1第一列每个变量的行数):
rgroup<-c()
n.rgroup<-c()
output_data<- NULL
for (varlabel in names(table_data)){
output_data <- rbind(output_data,table_data[[varlabel]])
rgroup <-c(rgroup,varlabel)
n.rgroup <-c(n.rgroup,nrow(table_data[[varlabel]]))
}
- 生成html 表格
htmlTable(output_data,align="rrrr",
rgroup=rgroup,
n.rgroup=n.rgroup,
rgroupCSSseparator="",
n.cgroup=n.cgroup,
rowlabel="",
caption="Table 1. Basic characteristics",
tfoot="<sup>a</sup>Also known as Breslow thickness")
image.png
- 微调
cgroup <- c("","Death","")
n.cgroup <- c(2,2,1)
colnames(output_data) <- gsub("[ ]*death","",colnames(output_data))
htmlTable(output_data,align="rrrr",
rgroup=rgroup,
n.rgroup=n.rgroup,
rgroupCSSseparator="",
cgroup=cgroup,
n.cgroup=n.cgroup,
rowlabel="",
caption="Table 1. Basic characteristics",
tfoot="<sup>a</sup>Also known as Breslow thickness",
ctable=TRUE)
image.png
- html 可以直接复制黏贴到word 修改
网友评论