Home > Software engineering >  Trying to define a function in R but it turns out to be object instead
Trying to define a function in R but it turns out to be object instead

Time:12-20

im a student who are currently studying R, and my lecturer gives me an assignment from one of the notebooks, here are the question:

We previously defined the generic power function and the instances square and cube this way:

power <- function(n) function(x) x^n
square <- power(2)
cube <- power(3)

If you instead defined this:

power <- function(x, n) x^n

How would you then define square and cube?

with the 1st example both power,square,and cube would become a function, that can calculate a vector

with x= (1,2,3,4,5) I tried solving the problem using a various of code combination such as

square=power(x,2) # it works, but it creates 'square' as an  object of x^2 instead of being a function,
square=power(,2) # telling me that x has to be defined and cant be empty
square= power(2) # I know it wouldn't work and it says n has to be defined which is... not a surprise

The book doesn't gives any example of this and I'm basically out of ideas on how to redefine the function, so any helps would be greatly appreciated, thanks for your attention!

CodePudding user response:

Given power <- function(x, n) x^n, you should define square like below

square <- function(x) power(x, 2)

CodePudding user response:

power <- function(x, n) x^n

square <- function(x) power(x, 2)
cube <- function(x) power(x, 3)

square(3) # 9
cube(3)   # 27

Given the following definition of x:

x = c(1,2,3,4,5)

You can run

> square(x)
[1]  1  4  9 16 25

And you will receive a numeric vector. If you do

square = power(x, 2)

You receive the same result. In the first example, square is a function. In the second example, square is a resulting vector of squares.

  • Related