Plumber Error: throw_if_func_is_not_a_function(private$func)

Viewed 87

I am using a simple for loop to calculate some mathematical formula. Eventually i want to see results on a web route. So for that i started using plumber, but it is showing an error. The R script looks like:

postgres.R

#* Get the progress of the script
#* @get /progress
# #* @param s
# library(plumber)
require(svMisc)

n <- 2 ^ 20
inside <- 0
total <- 0

function(){
  for (i in 1:100){
    x <- runif(n)
    y <- runif(n)
    r <- x ^ 2 + y ^ 2
    inside <- inside + sum(r <= 1)
    total <- total + n
    # print(inside * 4 / total)
    progress(i)
    if(i == 100) message("\nDone!")
  }
  message("function executed!")
}

I am running this using the commands:

library(plumber)
r<-plumb("postgres.R")

and getting this error in RStudio console:

Error in throw_if_func_is_not_a_function(private$func) : 
  `expr` did not evaluate to a function
1 Answers

This error is shown because there is code bewteen API endpoint definition lines (start with #*) and function definition function() {. The following code works fine when I launch prosgres.R clicking on "Run API" button in RStudio

require(svMisc)

n <- 2 ^ 20
inside <- 0
total <- 0

#* Get the progress of the script
#* @get /progress
# #* @param s
function(){
  for (i in 1:100){
    x <- runif(n)
    y <- runif(n)
    r <- x ^ 2 + y ^ 2
    inside <- inside + sum(r <= 1)
    total <- total + n
    # you do not capture this output
    progress(i)
    if(i == 100) message("\nDone!")
  }
  message("function executed!")
  # this is what will be returned by the API 
  list(total = total, indide = inside, check = inside * 4 / total)
}

Note that I've included a list to be returned by the endpoint so you can see the result in the web Swagger UI

Related