【发布时间】:2022-01-22 01:27:39
【问题描述】:
我是一名正在学习 R 的学生,我的讲师从其中一个笔记本中给我一个作业,问题如下:
我们之前以这种方式定义了通用幂函数以及实例正方形和立方体:
power <- function(n) function(x) x^n
square <- power(2)
cube <- power(3)
如果你改为定义这个:
power <- function(x, n) x^n
你会如何定义正方形和立方体?
在第一个例子中,幂、平方和立方都会变成一个函数,可以计算一个向量
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
这本书没有给出任何例子,我基本上不知道如何重新定义这个函数,所以任何帮助都将不胜感激,感谢您的关注!
【问题讨论】: