R 中的二元运算符/中缀函数是通用的吗?以及如何利用?
Are binary operators / infix functions in R generic? And how to make use of?
从 http://adv-r.had.co.nz/Functions.html or R: What are operators like %in% called and how can I learn about them? 我了解到可以使用 %
符号编写自己的 "binary operators" 或 "infix functioncs"。
一个例子是
'%+%' <- function(a, b) a*b
x <- 2
y <- 3
x %+% y # gives 6
但是如果它们来自预定义的 class 是否可以以通用方式使用它们(这样在某些情况下我不必使用 %
符号)?例如,如果 x + y
来自 class prod
.
,则应给出 6
是的,这是可能的:使用'+.<class name>' <- function()
。
例子
'+.product' <- function(a, b) a * b
'+.expo' <- function(a, b) a ^ b
m <- 2; class(m) <- "product"
n <- 3; class(n) <- "product"
r <- 2; class(r) <- "expo"
s <- 3; class(s) <- "expo"
m + n # gives 6
r + s # gives 8
安全注意事项
如果至少有一个参数来自相应的 class,m + 4
给你的是 2 * 4 = 8
而不是 2 + 4 = 6
,那么将调用新定义的函数。如果 classes 不匹配,您将收到一条错误消息(如 r + m
)。所以总而言之,请确保您要在 +
.
这样的基本功能背后建立一个新功能
从 http://adv-r.had.co.nz/Functions.html or R: What are operators like %in% called and how can I learn about them? 我了解到可以使用 %
符号编写自己的 "binary operators" 或 "infix functioncs"。
一个例子是
'%+%' <- function(a, b) a*b
x <- 2
y <- 3
x %+% y # gives 6
但是如果它们来自预定义的 class 是否可以以通用方式使用它们(这样在某些情况下我不必使用 %
符号)?例如,如果 x + y
来自 class prod
.
6
是的,这是可能的:使用'+.<class name>' <- function()
。
例子
'+.product' <- function(a, b) a * b
'+.expo' <- function(a, b) a ^ b
m <- 2; class(m) <- "product"
n <- 3; class(n) <- "product"
r <- 2; class(r) <- "expo"
s <- 3; class(s) <- "expo"
m + n # gives 6
r + s # gives 8
安全注意事项
如果至少有一个参数来自相应的 class,m + 4
给你的是 2 * 4 = 8
而不是 2 + 4 = 6
,那么将调用新定义的函数。如果 classes 不匹配,您将收到一条错误消息(如 r + m
)。所以总而言之,请确保您要在 +
.