本文翻译自:How can I view the source code for a function?
I want to look at the source code for a function to see how it works. 我想查看功能的源代码以了解其工作原理。 I know I can print a function by typing its name at the prompt: 我知道我可以通过在提示符下键入函数名称来打印该函数:
> t
function (x)
UseMethod("t")
<bytecode: 0x2332948>
<environment: namespace:base>
In this case, what does UseMethod("t")
mean? 在这种情况下, UseMethod("t")
是什么意思? How do I find the source code that's actually being used by, for example: t(1:10)
? 如何找到例如t(1:10)
实际使用的源代码?
Is there a difference between when I see UseMethod
and when I see standardGeneric
and showMethods
, as with with
? 有没有当我看到之间的差异UseMethod
,当我看到standardGeneric
和showMethods
,与with
?
> with
standardGeneric for "with" defined from package "base"
function (data, expr, ...)
standardGeneric("with")
<bytecode: 0x102fb3fc0>
<environment: 0x102fab988>
Methods may be defined for arguments: data
Use showMethods("with") for currently available ones.
In other cases, I can see that R functions are being called, but I can't find the source code for those functions. 在其他情况下,我可以看到正在调用R函数,但是找不到这些函数的源代码。
> ts.union
function (..., dframe = FALSE)
.cbind.ts(list(...), .makeNamesTs(...), dframe = dframe, union = TRUE)
<bytecode: 0x36fbf88>
<environment: namespace:stats>
> .cbindts
Error: object '.cbindts' not found
> .makeNamesTs
Error: object '.makeNamesTs' not found
How do I find functions like .cbindts
and .makeNamesTs
? 如何找到.cbindts
和.makeNamesTs
类的函数?
In still other cases, there's a bit of R code, but most of work seems to be done somewhere else. 在其他情况下,还有一些R代码,但是大多数工作似乎都在其他地方完成。
> matrix
function (data = NA, nrow = 1, ncol = 1, byrow = FALSE, dimnames = NULL)
{
if (is.object(data) || !is.atomic(data))
data <- as.vector(data)
.Internal(matrix(data, nrow, ncol, byrow, dimnames, missing(nrow),
missing(ncol)))
}
<bytecode: 0x134bd10>
<environment: namespace:base>
> .Internal
function (call) .Primitive(".Internal")
> .Primitive
function (name) .Primitive(".Primitive")
How do I find out what the .Primitive
function does? 我如何找出.Primitive
函数的作用? Similarly, some functions call .C
, .Call
, .Fortran
, .External
, or .Internal
. 同样,一些函数调用.C
, .Call
, .Fortran
, .External
,或.Internal
。 How can I find the source code for those? 我如何找到这些源代码?
#1楼
参考:https://stackoom.com/question/1Iflw/如何查看功能的源代码
#2楼
UseMethod("t")
is telling you that t()
is a ( S3 ) generic function that has methods for different object classes. UseMethod("t")
告诉您t()
是( S3 )泛型函数,具有用于不同对象类的方法。
The S3 method dispatch system S3方法调度系统
For S3 classes, you can use the methods
function to list the methods for a particular generic function or class. 对于S3类,可以使用methods
函数来列出特定泛型函数或类的方法。
> methods(t)
[1] t.data.frame t.default t.ts*
Non-visible functions are asterisked
> methods(class="ts")
[1] aggregate.ts as.data.frame.ts cbind.ts* cycle.ts*
[5] diffinv.ts* diff.ts kernapply.ts* lines.ts
[9] mon