I am trying to run a loop for univariate analysis for each covariate using the cmprsk package.

data(Melanoma, package = "MASS")
Melanoma <- Melanoma %>%mutate(
status = as.factor(recode(status, `2` = 0, `1` = 1, `3` = 2)))
###status 0=alive, 1=died from melanoma, 2=dead from other causes

covariates <- c("sex", "age", "ulcer","thickness")

univ_formulas <- sapply(covariates, function(x) {
  formula_string <- paste('Surv(time, status) ~', x)
  as.formula(formula_string)
  })

 univ_models <- lapply( univ_formulas, function(x){crr(x, data = Melanoma)})

After running the loop, I need to extract each hazard ratio, 95% CI, and p-value and put them on a table that could be exported as Excel or word file. Similar to what can be done with tbl_regression.

To extract the data, I tried:

tab1 = univ_models %>%tbl_regression(exponentiate = TRUE)

But it does not do what I need it to do.

1

There are 1 answers

1
Claudio Bravo On

I sorted this out.

# Load necessary libraries
library(survival)
library(broom)
library(dplyr)

#data manipulation
data(Melanoma, package = "MASS")
Melanoma <- Melanoma %>% mutate(
  status = as.factor(recode(status, `2` = 0, `1` = 1, `3` = 2))
)

covariates <- c("sex", "age", "ulcer", "thickness")

univ_formulas <- sapply(covariates, function(x) {
  formula_string <- paste('Surv(time, status) ~', x)
  as.formula(formula_string)
})

# Fitting the models
univ_models <- lapply(univ_formulas, function(x) {
  crr(x, data = Melanoma)
})

# Extracting and organizing results
tidy_results <- bind_rows(lapply(seq_along(univ_models), function(i) {
  tidy(univ_models[[i]], exponentiate = TRUE, conf.int = TRUE) %>%
    mutate(Covariate = covariates[i])
}))

# Print the tidy results
print(tidy_results)

library(dplyr)

# Selecting and renaming columns
selected_columns <- tidy_results %>%
  select(term, estimate, conf.low, conf.high, p.value)

# Renaming columns
renamed_columns <- selected_columns %>%
  rename(
    Covariate = term,
    HR = estimate,
    LowerCI = conf.low,
    UpperCI = conf.high,
    P.value =p.value
  )

renamed_columns

# Write the renamed and selected results to a CSV file
write.csv(renamed_columns, "selected_tidy_results.csv", row.names = FALSE)