Reputation: 905
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".
Upvotes: 0
Views: 561
Reputation: 14842
There two ways to extract a column from a data frame: $
and [[
. Below are a few examples that will all get you the same thing:
DF$Class1
DF[["Class1"]]
DF[[1]]
So using the last method above in combination with a for
loop accomplishes what you want.
for(i in 1:3){
plot(survfit(Surv(DF$t_rfs, DF$e_rfs == 1) ~ DF[[i]]), col = c("red", "blue"))
}
This is pretty basic so I recommend reading an introductory R book to get you going. It will save you from a lot frustration and is quicker than asking on SO.
Upvotes: 2