将向量长度不相等的列表转换为 R 中按地层的数据框



我有一个coxph函数的输出,它是通过地层估计的。我想将此输出从列表转换为数据框。 我为 coxph 运行的代码如下:

k <- coxph(Surv(cum.goodp, dlq.next) ~ rpc.length + cluster(itemcode) + strata(sector), data = nr.sample)
m <- summary(survfit(k))

有二十个不同的地层用于估计舵手。 这是列表的结构

List of 16
$ n        : int [1:20] 870 843 2278 603 6687 8618 15155 920 2598 654 ...
$ time     : num [1:870] 1 2 3 4 5 6 7 8 9 10 ...
$ n.risk   : num [1:870] 870 592 448 361 320 286 232 214 196 186 ...
$ n.event  : num [1:870] 246 126 77 34 33 25 18 18 8 6 ...
$ n.censor : num [1:870] 32 18 10 7 1 29 0 0 2 0 ...
$ strata   : Factor w/ 20 levels "sector=11","sector=21",..: 1 1 1 1 1 1 1 1 1 1 ...
$ surv     : num [1:870] 0.725 0.571 0.471 0.425 0.379 ...
$ type     : chr "right"
$ cumhaz   : num [1:870] 0.322 0.561 0.754 0.856 0.971 ...
$ std.err  : num [1:870] 0.015 0.017 0.0174 0.0174 0.0173 ...
$ upper    : num [1:870] 0.755 0.605 0.506 0.46 0.414 ...
$ lower    : num [1:870] 0.696 0.538 0.438 0.392 0.347 ...
$ conf.type: chr "log"
$ conf.int : num 0.95
$ call     : language survfit(formula = k)
$ table    : num [1:20, 1:7] 870 843 2278 603 6687 ...
..- attr(*, "dimnames")=List of 2
.. ..$ : chr [1:20] "sector=11" "sector=21" "sector=22" "sector=23" ...
.. ..$ : chr [1:7] "records" "n.max" "n.start" "events" ...
- attr(*, "class")= chr "summary.survfit"

我以前做过,但没有分层。 当我没有分层时,我使用以下方法:

col <- lapply(c(1 : 7), function(x) m[x])
tbl <- do.call(data.frame, col)

但是,当我在这里尝试这种方法时,我收到熟悉的错误:

cannot coerce class "c("survfit.cox", "survfit")" to a data.frame

所有列具有相同的名称,但它们的长度不同。 如果可能的话,我想在最终数据框中添加一列,其中包含结果所针对的特定地层。 有没有办法做到这一点? 它不必位于基本 R 中。 任何帮助将不胜感激。 非常感谢。

这个问题可以通过扫帚包中的整洁功能来解决。 对于上面的示例,代码为:

n <- survfit(k)
df <- tidy(n)

tidy 函数生成具有变量"strata"的数据框。 但是,它不提供中位数和平均值,但如果有人倾向于,则可以从数据框 df 中估计它们。 如果 survfit 对象有多个地层,则 glance(list) 无法提供中位数或平均值。

最新更新