This problem involves writing functions.
Some of the exercises are not tested by Dodona (for example the plots), but it is still useful to try them.
Power()
, that prints out the result of raising 2 to the 3rd power.
In other words, your function should compute \(2^3\) and print out the results to the console.
Run the command Power()
and verify if it prints 8
to the console.
Hint: use the
print()
function to output the result.
Power2()
, that allows you to pass any two numbers, x
and a
, and prints out the value of x^a
to the console.
You can do this by beginning your function with the line
Power2=function(x,a){
You should be able to call your function by entering, for instance,
Power2(3,8)
on the command line. This should output the value of \(3^8\), namely, 6561.
Using the Power2()
function that you just wrote, compute \(10^3\), \(8^{17}\), and \(131^3\).
Power3()
, that actually returns the result x^a
as an R object, rather than simply printing it to the screen.
That is, if you store the value x^a
in an object called result
within your function, then you can simply return()
this result, using the following line:
return(result)
The line above should be the last line in your function, before the }
symbol.
Test your function Power3()
by computing \(7^4\) using the function and assign the result to the variable power3.test
.
Notice that the result of \(7^4\) will only be printed to the console if you print power3.test
.
Try to recreate the following plot:
x
.Power3()
function, create a numeric vector \(f(x) = x^2\). Store the result in y
.plot()
function to verify that your variables x
and y
are correct.