0

Context

I would like to customize a function that uses non-standard evaluation (NSE) to fit the cox model. It works fine when I fit the cox model using the code.

But when I wrap the code into a custom function using NSE it reports an error.

Question

I don't know why using NSE in a custom function myfun is reporting an error and how to fix this error.

Reproducible code

library(survival)
library(rms)
data(cancer)

# works fine in normal code
dd = datadist(lung)
options(datadist = 'dd')
fit1 = cph(Surv(time, status) ~ rcs(meal.cal), data = lung)
fit1             
         
# report an error in self-define function using non-standard evaluation
myfun(data, var){
  
  dd = datadist(data)
  options(datadist = 'dd')
  fit1 = cph(Surv(time, status) ~ rcs({{var}}), data = data)
  fit1  
  
}

zhiwei li
  • 1,635
  • 8
  • 26

1 Answers1

1

Maybe you're looking for this?

myfun1 <- \(data, var) {
  # dd <- datadist(data)
  # options(datadist='dd')  ## what is this doing? I see no difference
  fo <- as.formula(paste('Surv(time, status) ~ rcs(', var, ')'))
  do.call('cph', list(fo, quote(data)))
}

myfun2 <- \(data, var) {
  fo <- as.formula(paste('Surv(time, status) ~ rcs(', deparse(substitute(var)), ')'))
  do.call('cph', list(fo, quote(data)))
}

myfun1(lung, 'meal.cal')  ## provide var as string
myfun2(lung, meal.cal)  ## provide var as name
# Frequencies of Missing Values Due to Each Variable
# Surv(time, status)           meal.cal 
#                  0                 47 
# 
# Cox Proportional Hazards Model
# 
# cph(formula = Surv(time, status) ~ rcs(meal.cal), data = data)
# 
# 
# Model Tests    Discrimination    
# Indexes    
# Obs        181    LR chi2      0.72    R2       0.004    
# Events     134    d.f.            4    R2(4,181)0.000    
# Center -0.3714    Pr(> chi2) 0.9485    R2(4,134)0.000    
#                   Score chi2   0.76    Dxy      0.048    
#                   Pr(> chi2) 0.9443                      
# 
#           Coef    S.E.   Wald Z Pr(>|Z|)
# meal.cal    -0.0006 0.0013 -0.48  0.6299  
# meal.cal'    0.0007 0.0051  0.14  0.8860  
# meal.cal''   0.0010 0.0261  0.04  0.9682  
# meal.cal''' -0.0132 0.0676 -0.19  0.8456  
jay.sf
  • 60,139
  • 8
  • 53
  • 110