Question



How to combine two functions with differing outputs and equations?

Professor,

# We have two functions: mainFirst, mainSecond.
# The function mainFirst will always be called first and the
# function mainSecond will be called second in our code.
# These functions are not very maintainable. The first part
# of both functions seems to be very similar. How could we
# improve this by making a third function?


#input data
x <- rnorm(100)

mainFirst <- function(x) {
x <- x + 1 + 2 - 1 + 3 - 4 + 1 + 1 + 10 + 35 - 12 + 9 + 19 +
1 + 1 + 5 + 1
summary(x)
}

mainSecond <- function(x) {
x <- x + 1 + 2 - 1 + 3 - 4 + 1 + 1 + 10 + 35 - 12 + 9 + 19 +
1 + 100 + 5 + 1
hist(x)
}

mainFirst(x)
mainSecond(x)

If we are supposed to combine these functions using a outer and inner function, then how will we account for the different equations for x
and the functions that are being returned for c?

Thank you





Answers and follow-up questions





Answer or follow-up question 1

You can do this by using conditional processing.
For example, a new helper function would contain the equation, and in the places where the
equations differ you would use 'if else' statements. If you're calling from mainFirst then it should be a 1,
otherwise it should be 100.
I encourage you to try solving the question with this information.



Sign in to be able to add an answer or mark this question as resolved.