尝试在 R 中定义一个函数,但结果是对象

pbi*_*cez 3 python r

我是一名正在学习 R 的学生,我的讲师给我布置了其中一个笔记本的作业,问题如下:

我们之前这样定义了通用幂函数以及实例平方和立方:

power <- function(n) function(x) x^n
square <- power(2)
cube <- power(3)
Run Code Online (Sandbox Code Playgroud)

如果您定义了这个:

power <- function(x, n) x^n
Run Code Online (Sandbox Code Playgroud)

那么你如何定义正方形和立方体?

在第一个例子中,幂、平方和立方都将成为一个函数,可以计算向量

x= (1,2,3,4,5) 我尝试使用各种代码组合来解决问题,例如

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
Run Code Online (Sandbox Code Playgroud)

这本书没有给出任何这样的例子,我基本上不知道如何重新定义函数,所以任何帮助将不胜感激,感谢您的关注!

Tho*_*ing 6

鉴于,你应该像下面这样power <- function(x, n) x^n定义square

square <- function(x) power(x, 2)
Run Code Online (Sandbox Code Playgroud)