ISLR Home

Question

p172

This problem involves writing functions. (a) Write a function, Power(), that prints out the result of raising 2 to the 3rd power. In other words, your function should compute 23 and print out the results.

Hint: Recall that x^a raises x to the power a. Use the print() function to output the result.

  1. Create a new function, Power2(), that allows you to pass any two numbers, x and a, and prints out the value of x^a. 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 38, namely, 6, 561.

  1. Using the Power2() function that you just wrote, compute 103, 817, and 1313.

  2. Now create a new function, 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()

return(result)

The line above should be the last line in your function, before the } symbol.

  1. Now using the Power3() function, create a plot of f(x) = x2. The x-axis should display a range of integers from 1 to 10, and the y-axis should display x2. Label the axes appropriately, and use an appropriate title for the figure. Consider displaying either the x-axis, the y-axis, or both on the log-scale. You can do this by using log=‘‘x’’, log=‘‘y’’, or log=‘‘xy’’ as arguments to the plot() function.

  2. Create a function, PlotPower(), that allows you to create a plot of x against x^a for a fixed a and for a range of values of x. For instance, if you call

> PlotPower (1:10 ,3)

then a plot should be created with an x-axis taking on values 1,2,…,10, and a y-axis taking on values 13,23,…,103.


12a

# Prints 2^3
Power = function() {
  # 2^3
  x = 2
  a = 3
  total = 1
  for (i in 1:a) {
    total = total * x
  }
  
  print(total)
}
Power()
## [1] 8

12b

Power2 = function(x, a) {
  
  total = 1
  for (i in 1:a) {
    total = total * x
  }
  
  print(total)
}

12c

Power2(10,3); 10^3
## [1] 1000
## [1] 1000
Power2(8, 17); 8^17
## [1] 2.2518e+15
## [1] 2.2518e+15
Power2(131,3); 131^3
## [1] 2248091
## [1] 2248091

12d

Power3_old = function(x, a) {
  
  total = 1
  for (i in 1:a) {
    total = total * x
  }
  
  return(total)
}

Power3 = function(x, a) {
  result = x^a
  return(result)
}

x = Power3(2,3); x
## [1] 8
Power3_old(1:10, 2)
##  [1]   1   4   9  16  25  36  49  64  81 100

12e

x = 1:10
y = Power3(x, 2)
plot(x,y)

Plot log()

plot(x,y, log = "xy")

12f

PlotPower = function(x, a) {
  plot(x, Power3(x, a), xlab = "PlotPower")
  
}

PlotPower(1:10 ,3)