Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

161
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda