I am trying automate a simple task in R using a function.
C
is list of character variables. mydata
- is the dataset.
Basically, I need to give each of the strings in vector C
as an input to the function.
dataset:
mydata <- structure(list(a = c(1L, 1L, 1L, 1L, 0L, 0L, 1L, 0L), b = c(4L,3L, 1L, 2L, 1L, 5L, 2L, 2L), c = c(1L, 1L, 1L, 1L, 1L, 1L, 1L,1L), d = c(0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L), t = c(42L, 34L, 74L,39L, 47L, 8L, 36L, 39L), s = c(0L, 0L, 0L, 0L, 0L, 1L, 0L, 0L)), .Names = c("a", "b", "c", "d", "t", "s"), row.names = c(NA,8L), class = "data.frame")
code:
c<-c("a","b","c","d")
plot<-function()
for (i in c)
{
fit<-survfit(Surv(s,t)~paste(i), dat=mydata)
ggsurvplot(fit, pval = TRUE)
}
plot()
I m facing the following error:
Error in model.frame.default(formula = Surv(mydata$s, mydata$t) ~ paste(i), : variable lengths differ (found for 'paste(i)')
I have tried the reformulate as well:
plot<-function()
for (i in c)
{
survfit(update(Surv(s,t)~., reformulate(i)), data=mydata)
ggsurvplot(fit, pval = TRUE)
}
plot()
but this code also gives this error:
Error in reformulate(i) : object 'i' not found
Any help to make this code work?
Thanks