是否可以在R中创建一元运算符?我知道可以像这样创建二元运算符:
setGeneric("%power%", function(x, y) x ^ y)
2 %power% 4
但是可以创建像-
这样的一元运算符。我试过像:
setGeneric("%-%", function(x) -x)
%-% 3
但它不起作用
答案 0 :(得分:5)
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
(解析器也支持二进制运算符:=
,这里没有记录,因为它不被基数R使用。)
请注意,唯一的自定义运算符(&#34; %x%
特殊二元运算符 x 可以替换为任何有效名称&#34;)是二进制。
因此,您唯一的选择是重载现有的一元运算符,分别为它编写方法。
答案 1 :(得分:1)
虽然我不熟悉setGeneric
,但我可以回答这个问题
是否可以在 R 中创建一元运算符?
是的,有点,但不是真的。你可以伪造它:
# LET'S USE A BINARY OPERATOR TO DEFINE A UNARY OPERATOR:
# THE SYMBOL /*/<- IS SUPPOSED TO LOOK LIKE PERCENT-WILDCARD-PERCENT--ASSIGNMENT-ARROW
`%/*/<-%` <- function ( name , FUN , safe = TRUE ) {
`%//%` <- paste0
NAME <- "%" %//% name %//% "%"
PARENT <- parent.frame ()
if ( safe && exists ( NAME , PARENT ) )
stop ( NAME %//% " exists." )
assign (
x = NAME ,
value = function ( x , ignored ) FUN ( x ) ,
envir = PARENT ) }
.. <- NULL # THIS IS WHAT I MEAN BY FAKING IT...
"-" %/*/<-% `-` # ... `%-%` IS ACTUALLY A BINARY OPERATOR....
1 %-%.. # ... IN THIS CALL, `..` IS THE SECOND ARGUMENT.
# [1] -1
1 %-%.. %-%..
# [1] 1
"t" %/*/<-% `t`
m <- matrix(1:4, 2)
m
# [,1] [,2]
# [1,] 1 3
# [2,] 2 4
m %t%..
# [,1] [,2]
# [1,] 1 2
# [2,] 3 4
"-" %/*/<-% `-`
# Error in "-" %/*/<-% `-` : %-% exists.
i <- floor ( runif ( 9 , min = 1 , max = 10 ) )
i
# [1] 2 3 2 1 7 3 9 5 9
unique(i)
# [1] 2 3 1 7 9 5
"u" %/*/<-% function ( x ) sort ( unique ( x ) )
i %u%..
# [1] 1 2 3 5 7 9