3

This is probably a very simple answer but can't seem to find a solution. I have a function which gives a set of parameters:

theta <-
function(
e = 0.2,l= 0.01,p= 0.05)
return(c(e=e,l=l,p=p))

So I can return from it a set of parameters, whilst changing one or more of them, e.g. by using

theta(e=0.1) #or
theta(l=0.1)

My problem is I want to call this function inside another function, where an input for that function is one of the variables.

So for example a function such as:

randFunc<-function(parameter,value){
s<-theta(parameter=value)
return(s)
}

Then use

randFunc("e",0.1) #or
randFunc("l",0.3)

However i'll get the error "Error in theta(parameter = value) : unused argument (parameter = value)"

I've tried a few things but can't seem to get the parameter "value" to be used within the theta function.

1
  • Sorry that should read randFunc("e",0.1) #or randFunc("l",0.3) Commented Apr 26, 2017 at 9:16

2 Answers 2

8

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 
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks Johan, this is also a great answer
3

You need to use a string in the call to randFunc, because the parameter you put in does not exist. Then, within the function you can use eval(parse(text = "something")) to use it as a non-string input for the theta function.

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 solution without the use of eval(parse()):

Change your randFunc to:

randFunc<-function(parameter,value){
  s <- theta()
  s[parameter] <- value
  return(s)
}

This is pretty elegant and will definitely find its way into future functions of my own (or even into current functions when it is time for revision).

1 Comment

Hmm, a quick google query showed me that this has something to do with eval(parse)) being suboptimal. Is there a better way to overcome this quite common problem? I'm asking because eval(parse()) can be found embarassingly often in my own functions...

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.