Using the value of a variable from one function in a second function from R
This is probably a very simple answer, but can't seem to find a solution. I have a function that gives a set of parameters:
theta <-
function(
e = 0.2,l= 0.01,p= 0.05)
return(c(e=e,l=l,p=p))
Therefore, I can return a set of parameters from it by changing one or more of them, for example. using
theta(e=0.1) #or
theta(l=0.1)
My problem is that I want to call this function inside another function, where the input for this function is one of the variables.
So, for example, a function like:
randFunc<-function(parameter,value){
s<-theta(parameter=value)
return(s)
}
Then use
randFunc("e",0.1) #or
randFunc("l",0.3)
However, I get the error "Error in theta (parameter = value): unused argument (parameter = value)"
I've tried several things, but I can't get the "value" parameter to be used in theta function.
source to share
You need to use a string in the call randFunc
because the parameter you are inserting does not exist. Then within the function, you can use eval(parse(text = "something"))
to use as non-string input for the function theta
.
randFunc<-function(parameter,value){
s<-theta(eval(parse(text = parameter)) = value)
return(s)
}
and then call it with
randFunc("e", 0.1)
@Cath provided a no-use solution eval(parse())
:
Change yours randFunc
to:
randFunc<-function(parameter,value){
s <- theta()
s[parameter] <- value
return(s)
}
It's pretty elegant and will definitely find its way into future features of my own (or even current features when it's time for a revision).
source to share