我们可以通过在控制台中键入方法名称来查看方法的源代码,如下例所示
> rowMeans
function (x, na.rm = FALSE, dims = 1L)
{
if (is.data.frame(x))
x <- as.matrix(x)
if (!is.array(x) || length(dn <- dim(x)) < 2L)
stop("'x' must be an array of at least two dimensions")
if (dims < 1L || dims > length(dn) - 1L)
stop("invalid 'dims'")
p <- prod(dn[-(id <- seq_len(dims))])
dn <- dn[id]
z <- if (is.complex(x))
.Internal(rowMeans(Re(x), prod(dn), p, na.rm)) + (0+1i) *
.Internal(rowMeans(Im(x), prod(dn), p, na.rm))
else .Internal(rowMeans(x, prod(dn), p, na.rm))
if (length(dn) > 1L) {
dim(z) <- dn
dimnames(z) <- dimnames(x)[id]
}
else names(z) <- dimnames(x)[[1L]]
z
}
<bytecode: 0x0000000021b2fec8>
<environment: namespace:base>
但我希望列出所有方法名称及其源代码一个接一个地提供。
以下内容为您提供了命名空间中的所有函数(包括未导出的函数):
ns = asNamespace('testthat')
function_code = eapply(ns, function (f) if (is.function(f)) capture.output(f))
ns_code = paste(
names(function_code),
lapply(function_code, paste, collapse = '\n'),
sep = ' = '
)
writeLines(ns_code, filename)
如果您只想捕获导出的函数,那么您需要添加一个额外的步骤,根据它们是否出现在getNamespaceExports(ns)
中来过滤符号:
exports = mget(getNamespaceExports(ns), ns, inherits = TRUE)
function_code = lapply(exports, function (f) if (is.function(f)) capture.output(f))
…
你可以使用水槽
# Setting up file
con <- file("/my/ouput/file/file.txt")
sink(con, append=TRUE)
sink(con, append=TRUE, type="message")
# Function to print source of
print("Function: ls")
ls
# Closing file
sink()
sink(type="message")
编辑在这里,我们打印从ggplot2到文件的所有功能:
# Listing all functions in package
library(ggplot2)
ggplot_functions <- ls("package:ggplot2")
# Setting up file
con <- file("c:/Users/H52Z/Desktop/source.txt")
sink(con, append=TRUE)
sink(con, append=TRUE, type="message")
# Prints all functions in package
for(fun in ggplot_functions) {
print(fun)
print(get(fun))
}
# Closing file
sink()
sink(type="message")