I have a cox model as such
cntrl_reduced <- coxph(Surv(time, status) ~ A B C, data=df)
When I run this I get no errors and the model works. I am writing this into a function and would like the predictor/covariables to be modified.
So I have the input to the function as
covariates= c('A', 'B', 'C')
and within the function I unlist this
covariates <- noquote(paste(covariates, collapse =' '))
covariates
output: A B C
However, when I try to run
cntrl_reduced <- coxph(Surv(time, status) ~ covariates, data=df)
I get the error
Error in model.frame.default(formula = Surv(time, status) ~ covariates, :
variable lengths differ (found for 'covariates')
How can I set it up so I can make my covariate input into a variable, rather than hard coded?
CodePudding user response:
You can't put that kind of object after the ~
symbol. Instead you need to use as.formula
. For example
covariates <- c("A", "B", "C")
formulaString <- paste("Surv(time, status) ~", paste(covariates, collapse=" "))
coxph(as.formula(formulaString), data=df)