我们可以通过在控制台中输入方法名称来查看方法的源代码,如下所示
> 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>但我想一个接一个地列出包中可用的所有方法名称及其源代码。
发布于 2019-04-02 18:58:57
您可以使用接收器
# 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")发布于 2019-04-02 19:10:19
下面为您提供了名称空间中的所有函数(包括未导出的函数):
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))
…https://stackoverflow.com/questions/55473029
复制相似问题