DarkMatter in Cyberspace
  • Home
  • Categories
  • Tags
  • Archives

View R Source Codes


The basic method for view a function's source code is input its name in R console without paranthesis:

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

The above output means this function is a generic function, which represents a group of functions. You can list this group with methods() function:

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

The final step is use getAnywhere() to view the souce codes (here we choose the function mean.default):

> getAnywhere(mean.default())
A single object matching ‘mean.default’ was found
It was found in the following places
  package:base
  registered S3 method for mean from namespace base
  namespace:base
with value

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: 0x611e5e0>
<environment: namespace:base>

But this method doesn't work for stats::hatvalues function.

Read the doc of hatvalues you can find it's just a wrapper of lm.influence, you can verify this through the following codes:

> mdl <- lm(hp ~ cyl + mpg, data = mtcars)
> hats <- hatvalues(mdl) 
> infs <- lm.influence(mdl)
> sum(hats - infs$hat)
0

Get the source of lm.influence(): getAnywhere(lm.influence)

You can see the res$hat in the source codes is just the \(h\) vector.



Published

Sep 10, 2018

Last Updated

Sep 10, 2018

Category

Tech

Tags

  • rlang 17

Contact

  • Powered by Pelican. Theme: Elegant by Talha Mansoor