R - Defining a function which recognises arguments not as objects, but as being part of the call

181 views Asked by At

I'm trying to define a function which returns a graphical object in R. The idea is that I can then call this function with different arguments multiple times using an for loop or lapply function, then plotting the list of grobs in gridExtra::grid.arrange. However, I did not get that far yet. I'm having trouble with r recognising the arguments as being part of the call. I've made some code to show you my problem. I have tried quoting and unquoting the arguments, using unqoute() in the function ("Object not found" error within a user defined function, eval() function?), using eval(parse()) (R - how to filter data with a list of arguments to produce multiple data frames and graphs), using !!, etc. However, I can't seem to get it to work. Does anyone know how I should handle this?

library(survminer)
library(survival)

data_km <- data.frame(Duration1 = c(1,2,3,4,5,6,7,8,9,10),
                      Event1 = c(1,1,0,1,1,0,1,1,1,1),
                      Duration2 = c(1,1,2,2,3,3,4,4,5,5),
                      Event2 = c(1,0,1,0,1,1,1,0,1,1),
                      Duration3 = c(11,12,13,14,15,16,17,18,19,20),
                      Event3 = c(1,1,0,1,1,0,1,1,0,1),
                      Area = c(1,1,1,1,1,2,2,2,2,2))

# this is working perfectly
ggsurvplot(survfit(Surv(Duration1, Event1) ~ Area, data = data_km))
ggsurvplot(survfit(Surv(Duration2, Event2) ~ Area, data = data_km))
ggsurvplot(survfit(Surv(Duration3, Event3) ~ Area, data = data_km))

myfun <- function(TimeVar, EventVar){
  ggsurvplot(survfit(Surv(eval(parse(text = TimeVar), eval(parse(text = EventVar)) ~ Area, data = data_km))
}

x <- myfun("Duration1", "Event1")
plot(x)
1

There are 1 answers

3
Roland On BEST ANSWER

You need to study some tutorials about computing on the language. I like doing it with base R, e.g., using bquote.

myfun <- function(TimeVar, EventVar){
  TimeVar <- as.name(TimeVar)
  EventVar <- as.name(EventVar) 

  fit <- eval(bquote(survfit(Surv(.(TimeVar), .(EventVar)) ~ Area, data = data_km)))
  ggsurvplot(fit)
}

x <- myfun("Duration1", "Event1")
print(x)
#works