I would like to know what are common in all package functions:
> sd
function (x, na.rm = FALSE)
{
if (is.matrix(x))
apply(x, 2, sd, na.rm = na.rm)
else if (is.vector(x))
sqrt(var(x, na.rm = na.rm))
else if (is.data.frame(x))
sapply(x, sd, na.rm = na.rm)
else sqrt(var(as.vector(x), na.rm = na.rm))
}
<environment: namespace:stats>
Should we provide the environment every time we write a package? or it is determined by where the function is located automatically ?
> var
function (x, y = NULL, na.rm = FALSE, use)
{
if (missing(use))
use <- if (na.rm)
"na.or.complete"
else "everything"
na.method <- pmatch(use, c("all.obs", "complete.obs", "pairwise.complete.obs",
"everything", "na.or.complete"))
if (is.data.frame(x))
x <- as.matrix(x)
else stopifnot(is.atomic(x))
if (is.data.frame(y))
y <- as.matrix(y)
else stopifnot(is.atomic(y))
.Internal(cov(x, y, na.method, FALSE))
}
<environment: namespace:stats>
It looks me that the function is more verbious, that exact calculation…so can you help me to explain how the function are different for a package than for own use?
Thanks;
The way you write your functions is the same for your personal script files as it is for your packages. The
<environment: ...>line indicates that the functions you are looking at are part of packages that have namespaces. If you use this feature in your package, R will take care of the details.Package namespaces, and writing packages in general, is a somewhat involved process, described in detail in the Writing R Extensions Manual. You may want to read a tutorial first, and read the manual after you have a rough idea of the basics..
The functions in official packages are indeed often more verbose than our personal functions. The main reason is that public packages, at least the widely-used ones, are designed to accommodate a wider range of inputs and options than any one typical user is likely to need. So there’s more code to account for edge cases and uncommon options. If the function uses C or Fortran code, as in the example
varabove, there will be some arcane language to deal with that too.So you don’t need to change anything about the way you write your personal functions if you want to make them into a package. However, going through the process of making the package may inspire you to improve the code anyways!