0

I am using the approxfun() function to get linear interpolation. I want to write a function which takes the results of approxfun() then shifts and scales it by an amount that I specify. I need to be able to call this new function just like I would call any other function.

Simplified version of my attempt:

set.seed(42)
x = rnorm(50)
y = rnorm(50, 5, 2)
fhat = approxfun(x, y, rule = 2)

new_function = function(fhat, a, b){

  new_fhat <- (function(fhat, a, b) a * fhat() + b)()

  return(new_fhat)

}

I expect the results to be the same as

2 * fhat(1) + 3

but instead when I run my function

new_function(fhat, a = 2, b = 3)

I get an error message:

*Error in (function(fhat, a, b) a * fhat() + b)() : argument "a" is missing, with no default*

2 Answers 2

2

You have four problems:

  1. new_fhat isn't passed the values of a and b from the new_function call, and can't see them because you are creating new ones in your function definition. This is actually a bit of a red herring because...
  2. The function you return should only have a single argument - the point at which you want to evaluate it.
  3. You are attempting to evaluate new_fhat immediately.
  4. You are trying to call fhat without an argument.

The solution is:

new_function = function(fhat, a, b){

  new_fhat <- function(v) a * fhat(v) + b

  return(new_fhat)

}

Results:

fhat(1)
[1] 5.31933
new_function(fhat,a=2,b=3)(1)
[1] 13.63866
2 * fhat(1) + 3
[1] 13.63866
Sign up to request clarification or add additional context in comments.

Comments

1

This is equivalent to the code in the question, but simplified:

new_function = function(fhat, a, b) {
  a * fhat() + b
}

But this is not correct, because in the posted code fhat requires an argument. For example, to make new_function(fhat, a = 2, b = 3) return the same results as 2 * fhat(1) + 3, you would have to add the parameter 1 inside the function:

new_function = function(fhat, a, b) {
  a * fhat(1) + b
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.