2

Is there any way I can define a function in R with a constant determined from a variable? I'm not sure how to say that better so here is an example.

> index<-3
> f<-function(x){x+index}
> f(4)
[1] 7     #Great!
> index<-20
> f(4)
[1] 24   #No! I still want to see 7!

Thank you!

Rubarb
  • 123
  • 1
  • 6
  • 4
    Advanced R's chapter on environments seems relevant: http://adv-r.had.co.nz/Environments.html – paljenczy Apr 27 '16 at 06:09
  • 1
    Might want to see http://stackoverflow.com/q/1169534 – BenBarnes Apr 27 '16 at 06:09
  • So I ultimately went with BenBarnes' approach for the short term but will keep reading up on environments as suggested by paljenczy to hopefully come up with something a little "nicer". Thank you both! – Rubarb Apr 27 '16 at 07:47
  • Two search terms that would likely have led you to a solution are "partial function" and "Currying". – drammock Apr 28 '16 at 16:27

2 Answers2

2

Look for ?lockBinding, your answer is here

index <- 3
lockBinding("index", globalenv())
index <- 4
#> Error: cannot change value of locked binding for 'index'
Community
  • 1
  • 1
JohnCoene
  • 2,107
  • 1
  • 14
  • 31
  • Thank you, but I'd like to be able to be able to change the value of "index" after the function is defined. Ideally, if I looked at the function, I would see this: function(x){x+3}. – Rubarb Apr 27 '16 at 06:12
2

A possible solution is to define your function within another function:

g <- function( index ){
  function( x ) x + index
}
index <- 3
f <- g( index )
f(4)
index<-20
f(4)

Now the output of g( index ) is a function which is defined within the (execution) environment of g. This function (f) will look at the value of indexin this environment, where it is fixed to 3. That's why it works, but maybe there is a simpler solution.

user7669
  • 638
  • 4
  • 13
  • Thank you! This looks like what BenBarnes was suggesting in a comment above but I didn't quite "get it" until I read your solution. – Rubarb Apr 27 '16 at 07:52