0

I was going through an R Function exercise, in this exercise we are required to create a function called bar_count that returns the least amount of aluminum bars required to fulfill an order, there are only two types of bars, 5kg bars and 1kg bars. The function should return F if the order has decimal it can only be exact numbers.

Here is what I came up with:

bar_count <- function(kg){

  num.of.five <- 0

  num.of.one <- 0

  five.kg <- kg/5

  if (kg%%5 == 0){

    num.of.five <-num.of.five + five.kg

  } else if(kg%%5 != trunc(kg%%5)){

    return(F)

  }else if (kg%%5 >= 1) {

    num.of.five <- num.of.five  + trunc(five.kg)

    num.of.one <- num.of.one + ((kg%%5))

  }

num.of.bars <- num.of.five + num.of.one

return (num.of.bars)

return(paste('qty of 5kg bars is:', num.of.five))

return(paste('qty of 1kg bars is:',num.of.one))

}

The problem I am having is with the two last commands where I ask R to return(paste()) the quantity of aluminum bars for the 5kg lot and the 1 kg lot, however it does not return any of those two,it only returns the total amount, I have tried with print() but it hasn't work either.

Thank you for taking the time to answer

Park
  • 14,771
  • 6
  • 10
  • 29
KingP
  • 3
  • 1
  • A function can only `return()` one value. Once the first `return()` is encountered, the function stops running. No further lines in the function body are executed. If you want to return multiple values, return a list: https://stackoverflow.com/questions/8936099/returning-multiple-objects-in-an-r-function – MrFlick Oct 13 '21 at 05:20

1 Answers1

0

Once you return from an R function, no code beyond the return statement will execute. Presumably you want to print before you return, so try using this version:

bar_count <- function(kg) {
    // ...

    print(paste('qty of 5kg bars is:', num.of.five))
    print(paste('qty of 1kg bars is:', num.of.one))

    return(num.of.bars)
}
Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360