0

I have a data frame (DF) that looks like this:

  Col1        Class1   Class2    Class3   t_rfs(days)  e_rfs
Sample_name1      A        B         A        750            1
Sample_name2      B        B         A        458            0
Sample_name3      B        B         A        1820           0
Sample_name4      B        A         B        1023           0
Sample_name5      A        A         B        803            0
Sample_name6      A        B         A        1857           1
Sample_name7      A        A         B        850            1

t_rfs_years = time to relapse free survival
e_rfs = event to relapse free survival
NB: this table is an example respect to the real case.

I simply would like to apply Kaplan Meier to each Class. The code I wrote is the following:

library(survival)
DF <- read.delim("DF.txt", header = T)
pdf("All_KM_plotted_together.pdf", paper = "USr")
par(mfrow=c(2,2))
surd <- survdiff(Surv(DF$t_rfs, DF$e_rfs == 1) ~ DF$Class1) 
plot(survfit(Surv(DF$t_rfs, DF$e_rfs == 1) ~ DF$Class1), col = c("red", "blue"))
surd <- survdiff(Surv(DF$t_rfs, DF$e_rfs == 1) ~ DF$Class2) 
plot(survfit(Surv(DF$t_rfs, DF$e_rfs == 1) ~ DF$Class2), col = c("red", "blue"))
surd <- survdiff(Surv(DF$t_rfs, DF$e_rfs == 1) ~ DF$Class3) 
plot(survfit(Surv(DF$t_rfs, DF$e_rfs == 1) ~ DF$Class3), col = c("red", "blue"))
dev.off()

I simply would like to write a loop that takes iteratively each "Class" at a time and run the script instead of write every time pieces of repeated code for each "Class".

4

1 回答 1

2

有两种方法可以从数据框中提取列:$[[. 下面是几个例子,它们都会让你得到同样的结果:

  • DF$Class1
  • DF[["Class1"]]
  • DF[[1]]

因此,将上面的最后一种方法与循环结合使用可以for完成您想要的。

for(i in 1:3){
    plot(survfit(Surv(DF$t_rfs, DF$e_rfs == 1) ~ DF[[i]]), col = c("red", "blue"))
}

这是非常基础的,因此我建议您阅读 R 入门书籍以帮助您入门。它将使您免于很多挫折,并且比询问 SO 更快。

于 2013-04-18T11:20:55.470 回答