在R中的多列的每个级别上执行功能

Perform function on each level of multiple columns in R

我需要在 data.table 中的多个列的每个级别上执行一个函数。例如,使用来自 survival:

lung 数据集
library(survival)
library(data.table)
library(dplyr)

data(lung)
setDT(lung)

vars <- c("sex", "ph.ecog")
lung[, (vars) := lapply(.SD, factor), .SDcols = vars]

fit <- tibble()
for (i in levels(lung[, vars ])){
temp <-
coxph(
  Surv(time, status) ~ i,
  data = lung
) %>% 
broom::tidy(exp=T)
fit <- bind_rows(fit, temp)
  }

这不起作用 - 我怎样才能成功?

您要运行 vars 列的每个级别还是每个 vars 列的函数?

对于后者,你可以这样做:

do.call(rbind,lapply(vars, function(x) {
  broom::tidy(coxph(reformulate(x, 'Surv(time, status)'), data = lung))
}))

#  term     estimate std.error statistic   p.value conf.low conf.high
#  <chr>       <dbl>     <dbl>     <dbl>     <dbl>    <dbl>     <dbl>
#1 sex2       -0.531     0.167     -3.18 0.00149    -0.859     -0.203
#2 ph.ecog1    0.369     0.199      1.86 0.0634     -0.0205     0.758
#3 ph.ecog2    0.916     0.225      4.08 0.0000448   0.476      1.36 
#4 ph.ecog3    2.21      1.03       2.15 0.0314      0.197      4.22 

为了简化一点,因为您已经在使用 data.table,您可以使用 rbindlist 而不是 do.call + rbind

为了 运行 您可以针对数据中的水平执行此操作:

do.call(rbind, lapply(vars, function(x) do.call(rbind,
        lapply(levels(lung[[x]]), function(y) 
    broom::tidy(coxph(reformulate(x, 'Surv(time, status)'), 
            data = lung[lung[[x]] == y]))))))