gpt4 book ai didi

r - 在 R 中创建一元运算符

转载 作者:行者123 更新时间:2023-12-05 07:24:19 25 4
gpt4 key购买 nike

是否可以在 R 中创建一元运算符?我知道可以像这样创建二元运算符:

setGeneric("%power%", function(x, y) x ^ y)
2 %power% 4

但是是否可以创建像-这样的一元运算符。我试过类似的东西:

setGeneric("%-%", function(x) -x)
%-% 3

但是没用

最佳答案

R 解析器不支持自定义一元运算符。

R language definition 中支持的运算符列表的副本:

-   Minus, can be unary or binary
+ Plus, can be unary or binary
! Unary not
~ Tilde, used for model formulae, can be either unary or binary
? Help
: Sequence, binary (in model formulae: interaction)
* Multiplication, binary
/ Division, binary
^ Exponentiation, binary
%x% Special binary operators, x can be replaced by any valid name
%% Modulus, binary
%/% Integer divide, binary
%*% Matrix product, binary
%o% Outer product, binary
%x% Kronecker product, binary
%in% Matching operator, binary (in model formulae: nesting)
< Less than, binary
> Greater than, binary
== Equal to, binary
>= Greater than or equal to, binary
<= Less than or equal to, binary
& And, binary, vectorized
&& And, binary, not vectorized
| Or, binary, vectorized
|| Or, binary, not vectorized
<- Left assignment, binary
-> Right assignment, binary
$ List subset, binary

(解析器还支持二元运算符 :=,此处未记录,因为 base R 未使用它。)

请注意,唯一的自定义运算符(“%x% 特殊二元运算符,x 可以替换为任何有效名称”)是二进制的。

因此,您唯一的选择是重载现有的一元运算符,分别为它编写一个方法。

关于r - 在 R 中创建一元运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55518829/

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