When writing our own R functions, sometimes we need to convert a string to a variable name to reduce the number of lines of code. The key to doing this is to pass the string with quotes (““) to the function, and then use the eval() and sym()/as.name() functions. Below is the R code to convert”anyI_new” and “all_blocks” to variable names.
library(tidyverse)
library(splines)
library(survival)
RCS_plot<-function(fx,myevent,variable){
dat<-read.csv( paste("D:\\myfolder\\",fx,"I_exer2.csv",sep=""), head=TRUE)
head(dat)
dat2 <-dat %>% mutate(new_stop=ifelse(start==stop, stop+1, stop))
check<-dat2 %>% filter(start>=new_stop)
nfit <- coxph(Surv(start,new_stop,eval(sym(myevent)))~ ns(eval(sym(variable)), df=4), dat2)
return(nfit)
}
### don't forget quote here
n_fit<-RCS_plot("any","anyI_new" ,"all_blocks")