Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

155
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda