R语言S4对象

创建类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
setClass(
# 类名
"TumorPrognosis",

# 数据列表
slots = c(
rawdata = "data.frame",
data = "data.frame",
markers = "character",
survival_year = "numeric",
group = "character",
cutoff = "list",
roc = "list",
ROCPlot = "list",
KMCurve = "list"
)
)

构造函数
initialize是内置的构造函数,
这也是范式方法的增加方法,如果是范式方法,可以直接给S4类增加这个方法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
setMethod("initialize", signature(.Object = "TumorPrognosis"),
function(.Object, tumorName, markers, survival_year){
.Object@markers = markers
.Object@survival_year = survival_year
.Object@rawdata = read.xlsx("01.data/prognosis1.xlsx", sheet = tumorName)

colnames(.Object@rawdata) = c(
"ID",
"inTime",
"outInfo",
"stage",
markers
)

.Object = ScreenData(.Object)
.Object = GroupedSample(.Object)
.Object = CalcBestCutoff(.Object)
.Object = getKMCurve(.Object)

.Object
})

如果不是范式,就需要先创建一个范式的,然后再添加到S4类上

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
setGeneric("getKMCurve", function(.Object) standardGeneric("getKMCurve"))
setMethod("getKMCurve", signature(.Object = "TumorPrognosis"), function(.Object){

for (data_set_name in c("train", "valid")){




sur_data = getGroupSameples(.Object, data_set_name)
for (marker in c("stage", .Object@markers)){
if(marker == "stage"){
legend_labs = c("Stage I/II", "Stage III/IV")
}else{
legend_labs = paste0(marker, c(" high risk", " low rish"))
}

group = paste0(marker, "_b")
surv = Surv(sur_data$futime, sur_data$fustat2)
formula_this = as.formula(paste0("surv", "~", group))

ggl = surv_fit(formula_this, data = sur_data)
surv_diff = survdiff(formula_this, data = sur_data)
p = ggsurvplot(ggl,
# palette = c("blue", "red"),
xlab = "Time (Years)",
ylab = "OS (percentage)",
break.x.by = 365,
break.y.by = 0.25,
ylim = c(0, 1),
xlim = c(0, 365 * .Object@survival_year),
legend.title = paste0("Log-rank p = ", format(1 - pchisq(surv_diff$chisq, length(surv_diff$n) -1), digits = 3)), # 图例标题
legend.labs = legend_labs,
size = 0.8,
# pval = T,
# pval.size = 5,
# pval.coord=c(365,0.05),
censor.shape=124,
censor.size=2,
font.main = c(16, "plain", "darkblue"),
font.x = c(10, "plain", "black"),
font.y = c(10, "plain", "black"),
font.tickslab = c(8,"plain", "black"),
font.legend = c(8,"plain","black"),
risk.table =F,
tables.height = 0.25,
# legend.labs=c("LPA","Non-LPA"),
legend = c(0.3,0.28),
fontsize=4.5,
conf.int=T,
conf.int.style='ribbon',
conf.int.alpha=0.1
# surv.median.line="hv"
)

p = p$plot +
scale_x_continuous(breaks = seq(0, 1825, 365), labels = seq(0, 5))

.Object@KMCurve[[data_set_name]][[marker]] = p
}
}
.Object

})

创建类实例

1
T05_5 = new("TumorPrognosis", "T05", c("CEA", "CA199", "AFP")  , 5)