R中的二进制运算符/中缀函数是否通用?以及如何利用? [英] Are binary operators / infix functions in R generic? And how to make use of?
问题描述
来自 http://adv-r.had.co.nz/Functions. html 或
From http://adv-r.had.co.nz/Functions.html or R: What are operators like %in% called and how can I learn about them? I learned that it is possible to write own "binary operators" or "infix functioncs" using the %
-sign.
One example would be
'%+%' <- function(a, b) a*b
x <- 2
y <- 3
x %+% y # gives 6
但是如果它们来自预定义的类,是否可以以通用的方式使用它们(因此在某些情况下,我不必使用%
-符号)?例如,如果x + y
来自类prod
,则应给出6
.
But is it possible to use them in a generic way if they are from a pre-defined class (so that in some cases I don't have to use the %
-sign)? For exampple x + y
shall give 6
if they are from the class prod
.
推荐答案
是的,这是可能的:使用'+.<class name>' <- function()
.
Yes, this is possible: use '+.<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
安全说明
如果至少一个参数来自对应的类m + 4
给您2 * 4 = 8
而不是2 + 4 = 6
,则将调用新定义的函数.如果类别不匹配,则会收到错误消息(例如r + m
).因此,总而言之,请确保要在诸如+
之类的基本功能之后建立一个新功能.
safety notes
The new defined functions will be called if at least one of the arguments is from the corresponding class m + 4
gives you 2 * 4 = 8
and not 2 + 4 = 6
. If the classes don't match, you will get an error message (like for r + m
). So all in all, be sure that you want to establish a new function behind such basic functions like +
.
这篇关于R中的二进制运算符/中缀函数是否通用?以及如何利用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!