Solution Review: Returning from a Function

In this review, we give a detailed analysis of the solution to this problem.

Solution: Returning from a Function

Press + to interact
evenOdd <- function(testVariable)
{
output <- vector("character", 0) # initializing an empty character vector
for(v in testVariable)
{
if(v %% 2 == 0)
{
# Insert even in vector if conditional statement satisfied
output <- c(output, "even")
}
else
{
# Insert odd in vector if conditional statement not satisfied
output <- c(output, "odd")
}
}
return(output) # returning the output vector.
# You can also simply write output here.
}
# Driver Code
evenOdd(c(78, 100, 2))

Explanation

The input to the function is an integer vector testVariable. We iterate over the entire vector. Then side by side populate the output vector that stores the result - even or odd for all the elements of the input vector. Later, we return the output vector.

Remember, output <- c(output, "even") is updating the variable output by appending an entry to the previous value of the variable output.