for循环函数给出:变量长度不同

时间:2016-05-11 19:46:19

标签: r

我正在尝试将for循环运行到函数中但得到错误:

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') 

输出应该是:

> 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 

1 个答案:

答案 0 :(得分:1)

您可以尝试使用as.formula()print()结果

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