Deals Of The Week - hours only!Up to 80% off on all courses and bundles.-Close
Creating functions
8. Functions with no return statement
If statements


Great work! In R, a function always returns a single value (an object). That object can be a number, string, vector, list, data frame, or anything else.

What happens if you don't explicitly define a return statement? In that case, R takes the last generated value/object inside the function and returns it as a result. Consider the following version of the count_age() function:

count_age <- function(birth_year){
  current_year <- as.numeric(format(Sys.time(), "%Y"))
  current_year - birth_year

This will return the exact same result as the function you defined in the last exercise with the explicit return statement. In this version, R simply takes the value of current_year - birth_year and returns it to the caller.

Generally, it's recommended that you explicitly use the return keyword in your functions. This makes the code more readable.


Check that the new version of the function count_age() works correctly. Pass in the year 1974.