这可能是一个简单的问题。但是,为什么这两个类不同呢?
class(call("assign", "x", 2))
[1] "call"
class(call("<-", "x", 2))
[1] "<-"
Run Code Online (Sandbox Code Playgroud)
为什么有一个<-调用类?
我相当确定这种行为是 S 的保留,与 R 无关。您正在练习 R 语言中定义相对不明确的部分:使用 S3 或 S4 的对象的类是什么?
我们转向源码寻找答案:
class
#> function (x) .Primitive("class")
pryr::show_c_source(.Primitive("class"))
#> class is implemented by R_do_data_class with op = 0
Run Code Online (Sandbox Code Playgroud)
这导致我们R_do_data_class然后R_data_class。该对象不是 S4,并且没有类属性,因此它无法恢复到某些默认值。对于 LANGSXP,它调用lang2str:
/* character elements corresponding to the syntactic types in the
grammar */
static SEXP lang2str(SEXP obj, SEXPTYPE t)
{
SEXP symb = CAR(obj);
static SEXP if_sym = 0, while_sym, for_sym, eq_sym, gets_sym,
lpar_sym, lbrace_sym, call_sym;
if(!if_sym) {
/* initialize: another place for a hash table */
if_sym = install("if");
while_sym = install("while");
for_sym = install("for");
eq_sym = install("=");
gets_sym = install("<-");
lpar_sym = install("(");
lbrace_sym = install("{");
call_sym = install("call");
}
if(isSymbol(symb)) {
if(symb == if_sym || symb == for_sym || symb == while_sym ||
symb == lpar_sym || symb == lbrace_sym ||
symb == eq_sym || symb == gets_sym)
return PRINTNAME(symb);
}
return PRINTNAME(call_sym);
}
Run Code Online (Sandbox Code Playgroud)
您可以看到该函数特例了许多具有自己的类的函数调用。
我认为 R 源代码中当前没有使用这些类,但您可以自己使用它们:
f <- function(x) UseMethod("f")
f.if <- function(x) "If statement"
f.while <- function(x) "While loop"
x <- quote(if (a) TRUE)
f(x)
#> "If statement"
y <- quote(while(TRUE){})
f(y)
#> "While loop"
Run Code Online (Sandbox Code Playgroud)
(当然,实际这样做是一个坏主意,因为这是该语言的一个极其深奥的角落,没有人会理解它是如何工作的)
| 归档时间: |
|
| 查看次数: |
776 次 |
| 最近记录: |