gpt4 book ai didi

r - 将算术运算符视为函数

转载 作者:行者123 更新时间:2023-12-03 21:37:13 25 4
gpt4 key购买 nike

我读过 R 中的一切都是函数。所以我想知道“+”是否也是一个函数
如果我们可以写这样的东西:

xx <- c(1,2,3)
yy <- c(1,2,3,4,5,6)

# zz is the sum of the two lengths
zz <- +(if(exists("xx")) length(xx), if(exists("yy")) length(yy))

最佳答案

是的你可以:

xx <- c(1,2,3)
yy <- c(1,2,3,4,5,6)

# zz is the sum of the two lengths
zz <- `+`(if(exists("xx")) length(xx), if(exists("yy")) length(yy))
#[1] 9

要调用没有语法有效名称的对象(例如,如果您执行类似 + 之类的操作,则会隐式调用的函数 1 + 2),您需要将名称括在反引号 (`) 或引号("或 ')中.

另请参阅 R Language Definition 的第 3.1.4 节:

Except for the syntax, there is no difference between applying an operator and calling a function. In fact, x + y can equivalently be written `+`(x, y). Notice that since ‘+’ is a non-standard function name, it needs to be quoted.



在您的代码中,您收到错误:
Error: unexpected ',' in "zz <- +(if(exists("xx")) length(xx),"

这是因为您没有调用(二进制)函数 "+" , 但一元运算符 + ,它不需要函数参数,因此将括号解释为“算术”运算符。它们之间不允许有逗号。

关于r - 将算术运算符视为函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33349387/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com