SWR
SWR

Reputation: 505

How to include a graphical output to function

I have written a function to calculate the BMI and have the code to create a corresponding graphical output. My goal is to include the graphical output into the function so that I get the plot by just using the function.

My current code:

BMI <- function(meter, kg){
  BMI <- kg/(meter^2)
  return(BMI)
}
BMI(1.8,70)

x <- seq(1.5, 1.9, by = 0.001)
y <- seq(30, 200, by = 0.5)
z <- outer(x, y, FUN = function(x, y) {BMI(x, y)})
contour(x, y, z, nlevels = 10, method = "edge", main = "BMI")
abline(h = 70, v=1.8, col="darkgrey") 
points(1.8,70, col="red", cex=2, pch=16, bg="red")

By just modifying the meter & kg in the function I would like to get a diagram with the correct line and point positioning. I started with the code below - however it does not work, yet.

graphicalBMI <- function(meter, kg){
  BMI <- kg/(meter^2)
  x <- seq(1.5, 1.9, by = 0.001)
  y <- seq(30, 200, by = 0.5)
  z <- outer(x, y, FUN = function(x, y) {graphicalBMI(x, y)})
  contour(x, y, z, nlevels = 10, method = "edge", main = "BMI")
  abline(h = kg, v= meter, col="darkgrey") 
  points(meter, kg, col="red", cex=2, pch=16, bg="red")
  return(graphicalBMI)
}

Upvotes: 0

Views: 53

Answers (1)

digEmAll
digEmAll

Reputation: 57210

The problem of your second function is that it produces an infinite-recursion.
If you change it like this you'll get what you want:

graphicalBMI <- function(meter, kg, showPlot=TRUE){

  BMI <- kg/(meter^2)

  if(showPlot){
    x <- seq(1.5, 1.9, by = 0.001)
    y <- seq(30, 200, by = 0.5)

    # here we call graphicalBMI by setting showPlot=F to avoid infinite recursion
    z <- outer(x, y, FUN = function(x, y) {graphicalBMI(x, y, FALSE)})
    contour(x, y, z, nlevels = 10, method = "edge", main = "BMI")
    abline(h = kg, v= meter, col="darkgrey") 
    points(meter, kg, col="red", cex=2, pch=16, bg="red")
  }
  return(BMI)
}


# usage example:
graphicalBMI(1.8,70) # plot produced

graphicalBMI(1.8,70,FALSE) # no plot produced

Upvotes: 1

Related Questions