Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

153
Views
Trying to define a function in R but it turns out to be object instead

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!

over 4 years ago · Santiago Trujillo
2 answers
Answer question

0

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

square <- function(x) power(x, 2)
over 4 years ago · Santiago Trujillo Report

0

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.

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!