ggsurvplot:从函数调用时无法使用survfit

时间:2018-06-11 09:58:43

标签: r ggplot2

我试图绘制一个生存情节,并在尝试将我的幸存函数移动到主函数时遇到问题,我可以将其称为不同的数据集。当我运行代码时

fit<- survfit(Surv(time, status) ~ sex, data = lung)

allsurv <- function(fit){
ggsurvplot(
fit,
pval = TRUE,
pval.coord = c(200, 0.10), 
conf.int = TRUE,
xlab = "Days",
ggtheme = theme_light(), 
surv.median.line = "hv", 
legend.labs = c("Female","Male"),
legend.title = "",
palette = c("#8C3F4D","#3E606F")) + 
scale_y_continuous(expand = c(0.02, 0.02),breaks = seq(from = 0, to = 1, by = 0.1),labels=percent) + 
scale_x_continuous(expand = c(0.006, 0.006),
                   limits = c(0,366*12), breaks = seq(0, 4392, 100))
}

allsurv(fit)

该功能正常绘制enter image description here

然而,当我从一个函数调用了survfit时:

fit_all <- function(x){
 survfit(Surv(time, status) ~ sex, data = x)
}

allsurv(fit_all(lung))

我收到错误:&#34; eval中的错误(适合$ call $ data):object&#39; x&#39;找不到&#34;

对我做错的任何想法?

2 个答案:

答案 0 :(得分:1)

我设法让它发挥作用。对于有同样问题的其他人。问题似乎是由自己调用函数或从不同函数返回的函数引起的。

 fit_all(lung) 

返回Call:survfit(公式= Surv(时间,状态)〜性别,数据= x)

fit 

返回Call:survfit(公式= Surv(时间,状态)〜性别,数据=肺)

似乎ggsurvplot将调用中的数据视为绘图的数据,并从另一个函数'data = x'调用。似乎过去的方法是在ggsurvplot中的幸存函数之前定义数据。

allsurv <- function(fit, x){
ggsurvplot(
data = x,
fit,
pval = TRUE,
pval.coord = c(200, 0.10), 
conf.int = TRUE,
xlab = "Days",
ggtheme = theme_light(), 
surv.median.line = "hv", 
legend.labs = c("Female","Male"),
legend.title = "",
palette = c("#8C3F4D","#3E606F")) + 
scale_y_continuous(expand = c(0.02, 0.02),breaks = seq(from = 0, to = 1, by = 0.1),labels=percent) + 
scale_x_continuous(expand = c(0.006, 0.006),
                   limits = c(0,366*12), breaks = seq(0, 4392, 100))
}

allsurv(fit_all(lung), lung)

答案 1 :(得分:1)

Survminer包含一个函数groupby(),该函数充当groupdf = df.groupby('ID') for name,group in groupdf: for i in range(2): newdf.loc[newdf.ID==name, 'X0_{}'.format(i+1)] = \ group.sort_values(by=['IsTrue','DistanceToIdx'],ascending=True)['X'].values[i] newdf.loc[newdf.ID==name, 'X1_{}'.format(i+1)] = \ group.sort_values(by=['IsTrue','DistanceToIdx'],ascending=True)['X'].values[i+2] 的包装器。如果使用surv_fit而不是survfit,则返回对象的“调用”将包括整个数据帧,而不仅仅是surv_fit。在公式中调用ggsurvplot时,效果更好:

https://www.rdocumentation.org/packages/survminer/versions/0.4.6/topics/surv_fit

survfit