# start out with a number to test
x <- 3
# you'll want your function to return this number
x^2
square <- function() {
}
# test it out
square(x)
square(53)
53^2 # does this match?2.5 Functions
Open the slides in a new tab here.
Exercises
- Square a number. You’re tired of writing
x^2when you want to squarex, so you want a function to square a number. You can call itsquare(). I showed this in the slides, now try on your own!
- Raise to any power. You don’t just want to square numbers, you want to raise them to higher powers too. Make a function that uses two arguments,
xfor a number, andpowerfor the power. Call itraise().
raise <- function() {
}
# test with
raise(x = 2, power = 4)
# should give you
2^4- Change your
raise()function to default to squaringxwhen the user doesn’t enter a value forpower.
# test
raise(x = 5)
# should give you
5^2