[英]R, how to put all the column names of a dataframe into a formula?
我正在嘗試按照本教程將R
中的多元 Cox 回歸分析應用於我的數據集。 特別是,我正在嘗試應用以下 function coxph()
:
install.packages(c("survival", "survminer"));
library("survival");
library("survminer");
data("lung");
res.cox <- coxph(Surv(time, status) ~ age + sex + ph.ecog, data = lung)
summary(res.cox)
如您所見,在這種情況下,特征的名稱 ( age + sex + ph.ecog
) 已手動插入到公式中。
相反,在我的例子中,我有數以千計的特征,所以我不能手動添加它們的名字。 我需要找到一種自動插入它們的方法。 我試圖在以前的案例中這樣做,但沒有成功。 這是我嘗試過的:
featureNames <- paste(colnames(lung), collapse = " + ")
res.cox <- coxph(Surv(time, status) ~ featureNames, data = lung)
我收到此錯誤消息:
Error in model.frame.default(formula = Surv(time, status) ~ featureNames, :
variable lengths differ (found for 'featureNames')
有人能幫我嗎? 謝謝! 我在運行 Linux Ubuntu 18.04.5 LTS/ 的電腦上使用R
版本 3.6.3
使用parse()
和eval()
就可以了。
featureNames <- paste(colnames(lung), collapse = " + ")
res.cox <- coxph(Surv(time, status) ~ eval(parse(text = featureNames)), data = lung)
使用reformulate,首先設置一個默認公式:
fS <- Surv(time, status) ~ .
假設您事先知道這些功能:
colnames(lung)
[1] "inst" "time" "status" "age" "sex" "ph.ecog"
[7] "ph.karno" "pat.karno" "meal.cal" "wt.loss"
features = c("ph.karno","age","meal.cal","wt.loss")
fs = reformulate(features, fS[[2]])
coxph(fs, data = lung)
Call:
coxph(formula = fs, data = lung)
coef exp(coef) se(coef) z p
ph.karno -9.152e-03 9.909e-01 7.327e-03 -1.249 0.212
age 1.629e-02 1.016e+00 1.168e-02 1.395 0.163
meal.cal 5.087e-06 1.000e+00 2.391e-04 0.021 0.983
wt.loss -1.057e-03 9.989e-01 6.884e-03 -0.154 0.878
Likelihood ratio test=5.84 on 4 df, p=0.2113
n= 171, number of events= 124
(57 observations deleted due to missingness)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.