robust
robust

Reputation: 634

How to test a function within a function in R?

I would like to use the testthat package to test a function that is enclosed by another function.

How can I test such a function?

If this is not possible, how can I refactor the code so that testing objective_function is possible?


Illustrative Example

model <- function(parameter) {
  objective_function <- function(x) {
    (x - p)^2
  }

  # Make parameter integer
  p <- round(parameter)
  result <- optimize(objective_function, c(-10, 10))
  result$minimum
}

# Works
testthat::expect_equal(model(4.2), 4)

# Does not work
# And how would you pass p to the following?
testthat::expect_equal(objective_function(4.2), 4)
#> Error in objective_function(4.2): could not find function "objective_function"

Created on 2019-05-13 by the reprex package (v0.2.1)

Upvotes: 0

Views: 1636

Answers (2)

JKing
JKing

Reputation: 73

Assuming you're using Rstudio, trying both debugonce(model) and debugonce(objective_function) could be your answer.

Upvotes: 0

thc
thc

Reputation: 9705

Another approach: explicitly set function scope within model function:

objective_function <- function(x) {
  (x - p)^2
}

model <- function(parameter) {
  # Make parameter integer
  p <- round(parameter)
  environment(objective_function) <- environment()
  result <- optimize(objective_function, interval=c(-10, 10))
  result$minimum
}

model(4.2)

p <- 4
objective_function(4.2)

Upvotes: 1

Related Questions