简体   繁体   中英

Pass Objects into User Defined Function

I would like to create a user defined function to run coxph over a list of variables. This formula runs just fine:


summary(coxph(
  Surv(var1, factor(var1)) ~ var3, 
  data = df_wts))

But then if I try to turn it into a function, I keep getting an "object not found" warning:


cox_fun <- function(x, y) {
summary(coxph(
  Surv(x, factor(y)) ~ var3, 
  data = df_wts))

Have tried everything, enquo(x), {{}}, [[]], ,., as.name(), etc.

Any explanation for why this is happening? Environment? Thanks!

First your var3 seems not defined. Your var1 is your second code x and y which is a bit strange and finally you should end the function with } . Try this code:

cox_fun <- function(x, y) {
  summary(coxph(
    Surv(x, factor(x)) ~ y, 
    data = df_wts))}

figured this out. Main issue was (I think) that the environment wasn't carrying over. I fixed it by adding in calls to the dataframe itself. Not sure if this is helpful, but here's the updated code

A few extra things added:

I wanted to just input a single value, so I named variables with a paste function

Then I added that with the database to make sure Surv() actually processed it properly

Then a quick function to apply the function over my list of variables. Cheers!


# Calculate Cox Function 
cox_fun <- function(i) {
  x <- paste0("fu_time_", enexprs(i))
  y <- paste0("fu_status_", enexprs(i))
  cox <- summary(coxph(
    Surv(df_wts[[x]], factor(df_wts[[y]]))~ prophied + 
      age + male + race_ethnicity + patient_regional_location + Obesity + Smoking + total_admits + chf + copd + diabwc + mld + cevd, 
    weights = ipw, 
    id = patient_id, 
    data = df_wts))
  tribble(~Outcome, ~`Odds Ratio`, ~`95% CI`, ~`P Value`,
          paste(i),
          round(cox$conf.int[1,1], digits = 2),
          paste0(round(cox$conf.int[1,3], digits = 2), "-", round(cox$conf.int[1,4], digits = 2)),
          round(cox$coefficients[1,6], digits = 2))
  
}

# Generate DF 
do.call(rbind, lapply(ade_int, cox_fun)) %>% 
  #write_csv(paste(Sys.Date(), "Table 3.csv")) 
  print(n=50)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM