R语言查看源代码

文章内容转载自:https://zhidao.baidu.com/question/1386898038982952580.html

方法1:

  直接输入函数对象名称

方法2:

  对于封装的函数,使用methods(fun)查看封装的所有的函数,然后输入fun.相应的函数(如:mean.default)

> mean
function (x, ...) 
UseMethod("mean")
<bytecode: 0x0b72ac74>
<environment: namespace:base>

> methods(mean) [1] mean.Date mean.default mean.difftime mean.POSIXct mean.POSIXlt see '?methods' for accessing help and source code

> mean.default function (x, trim = 0, na.rm = FALSE, ...) { if (!is.numeric(x) && !is.complex(x) && !is.logical(x)) { warning("argument is not numeric or logical: returning NA") return(NA_real_) } if (na.rm) x <- x[!is.na(x)] if (!is.numeric(trim) || length(trim) != 1L) stop("'trim' must be numeric of length one") n <- length(x) if (trim > 0 && n) { if (is.complex(x)) stop("trimmed means are not defined for complex data") if (anyNA(x)) return(NA_real_) if (trim >= 0.5) return(stats::median(x, na.rm = FALSE)) lo <- floor(n * trim) + 1 hi <- n + 1 - lo x <- sort.int(x, partial = unique(c(lo, hi)))[lo:hi] } .Internal(mean(x)) } <bytecode: 0x0283bb44> <environment: namespace:base>
方法3:
以上两种方法仅针对于泛型函数,例如lm的则没有,此时使用*隐藏起来了,则可以使用
getAnywhere('lm')
> methods(lm)
[1] lm.fit       lm.influence lm.wfit     
see '?methods' for accessing help and source code
Warning message:
In .S3methods(generic.function, class, parent.frame()) :
  function 'lm' appears not to be S3 generic; found functions that look like S3 methods
举例:随机森林中的randomForest函数
> methods("randomForest")
[1] randomForest.default* randomForest.formula*
see '?methods' for accessing help and source code
> getAnywhere('randomForest.default')
关于以上方法均不可解决的问题:核心代码需要到网站上下载专用的包
很多函数的核心是用C或FORTRAN等写的,利用.C(),.FORTRAN()等函数调用。这种做法是出于计算效率的考虑,
这时核心代码就需要到相应软件包主页上下载。比如randomForest是用FORTRAN写的,这时就需要去软件包的主页去下载“package source”。
以上转载自http://blog.renren.com/share/294932861/12888149119 

 
 
 
原文地址:https://www.cnblogs.com/liuting1990/p/6748480.html