I have a (long) customized function and am wondering if there's a way to apply gsub to tweak the syntax for that function.
As an illustration, my original customized function looks like:
mymodel <- function(dataname){
m <- lm(DV ~ IV, data = dataname)
[a bunch of other lines to plot the results]
}
And I'd like to create another customized function like:
mymodel2 <- function(dataname){
m <- lm(DV ~ IV COVARIATE, data = dataname)
[same lines as in mymodel syntax to plot the results]
}
Ideally I'm thinking of a solution like:
mysyntax <- '
m <- lm(DV ~ IV, data = datname)
[other lines to plot the results]
'
mysyntax2 <- gsub('DV ~ IV', 'DV ~ IV COVARIATE', mysyntax)
# this will keep all the other lines identical to mysyntax, other than the model specification
and then inputting this to create my customized function:
mymodel <- function(datname){mysyntax}
mymodel2 <- function(datname){mysyntax2}
I might be missing something very obvious, but I can't seem to find a way to pass a vector (mysyntax
or mysyntax2
) as an argument to a function.
Any help would be greatly appreciated!
CodePudding user response:
Suggest just defining a basic function mymodel_
with wrappers:
mymodel_ <- function(dataname, formula){
m <- lm(formula, data = dataname)
}
mymodel1 <- function(dataname, formula = DV ~ IV) mymodel_(dataname, formula)
mymodel2 <- function(dataname, formula = DV ~ IV COVARIATE) mymodel_(dataname, formula)
1a) or define a factory function that creates other functions
mymodelFactory <- function(formula) {
function(dataname) {
m <- lm(formula, data = dataname)
}
}
mymodel1 <- mymodelFactory(DV ~ IV)
mymodel2 <- mymodelFactory(DV ~ IV COVARIATE)
2) Although I don't really recommend this you can modify the mymodel
function shown in the Note at the end like this:
mymodel3 <- mymodel
body(mymodel3)[[2]][[3]][[2]] <- DV ~ IV COVARIATE
mymodel3
3) This is not really recommended either but it can also be done using strings
s <- sub("DV ~ IV", "DV ~ IV COVARIATE", format(mymodel))
mymodel4 <- eval(parse(text = s))
mymodel4
Note
mymodel <- function(dataname) {
m <- lm(DV ~ IV, data = dataname)
}