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.

+3


source to share


2 answers


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).

+3


source


Another way is to use do.call:



randFunc <- function(parameter, value){
    L = list(value)
    names(L) <- parameter
    do.call(theta, L)
}

> randFunc('e', 0.1)
   e    l    p 
0.10 0.01 0.05 
> randFunc('l', 0.3)
   e    l    p 
0.20 0.30 0.05 

      

+8


source







All Articles