Skip to content

Convert numerical value into function which returns numerical value

2 messages · Rainer M Krug, William Dunlap

#
Hi

I want convert, in a function, an argument from a numerical value to a
function which returns this value.:

My Code:

--8<---------------cut here---------------start------------->8---
dep <- 13
dep <- function() {dep}
dep
--8<---------------cut here---------------end--------------->8---

This is what I get:
#+RESULTS:
,----
| function(PAI) { dep }
`----

This is what I want
,----
| function(PAI) { 13 }
`----

I thought about using eval(dep), but this gives me the effectively the
same.

Is it possible to achieve what I want? I somehow have the feeling this
is not that easily possible, as the code in the function definition is
only evaluated when the function is evaluated.

I could obviously do something like

--8<---------------cut here---------------start------------->8---
dep <- 13
depVal <- dep
dep <- function() {depVal}
dep()
--8<---------------cut here---------------end--------------->8---

But is there a better solution? 

Thanks,

Rainer
#
You can make such functions by using the fact that a function
(really, a 'closure') always has access to the environment in
which the function was created.  E.g.
  makeConstantFunction <- function(constant) {
      force(constant) # evaluate the argument now
      function(PAI) {
          constant
      }
  }
  f17 <- makeConstantFunction(17)
  flog17 <- makeConstantFunction(log(17))
  f17(111)
  # [1] 17
  flog17(111)
  # [1] 2.833213

If you print f17 and flog17 they will look the same, except for
their environments and you have to inspect those to see why
they act differently.

  ls.str(environment(f17))
  # constant :  num 17
  ls.str(environment(flog17))
  # constant :  num 2.83

If you really want the functions to look different you can use
substittute or bquote, but that is also a bit mysterious (you need the
eval()
their outputs):
  g17 <- eval(substitute(function(PAI)x, list(x=17)))
  h17 <- eval(bquote(function(PAI).(x), list(x=17)))
  g17(10)
  [1] 17
  h17(10:1)
  [1] 17




Bill Dunlap
TIBCO Software
wdunlap tibco.com
On Thu, Apr 9, 2015 at 5:39 AM, Rainer M Krug <Rainer at krugs.de> wrote: