user2300940
user2300940

Reputation: 2385

for loop in function gives: variable lengths differ

I am trying to run a for loop into a function but get an error:

for(i in colnames(test)){
  coxph(Surv(Time, Status)~ i,  data=as.data.frame(test))
}

> head(colnames(test))
[1] "hsa_let_7a_5p" "hsa_let_7b_3p" "hsa_let_7b_5p" "hsa_let_7c_5p" "hsa_let_7d_3p" "hsa_let_7d_5p"

Error in model.frame.default(formula = Surv(Time, Status) ~ i, data = as.data.frame(test)) : 
  variable lengths differ (found for 'i') 

The output is supposed to be:

> coxph(Surv(Time, Status)~ hsa_let_7b_5p,  data=as.data.frame(test))
Call:
coxph(formula = Surv(Time, Status) ~ hsa_let_7b_5p, data = as.data.frame(test))


               coef exp(coef) se(coef)    z    p
hsa_let_7b_5p 0.169     1.184    0.173 0.98 0.33

Likelihood ratio test=0.94  on 1 df, p=0.333
n= 91, number of events= 45 

Upvotes: 0

Views: 788

Answers (1)

HubertL
HubertL

Reputation: 19544

You can try using as.formula(), and print() the result

for(i in colnames(test)){
  print(coxph(as.formula(paste0("Surv(Time, Status)~", i)),  data=as.data.frame(test)))
}

Upvotes: 2

Related Questions