Ken Williams
Ken Williams

Reputation: 24005

R selective importing from namespaces

If I'm writing an R package, I can use importFrom(plyr,colwise) to selectively import the colwise() function into my namespace. If I'm running code interactively at the command line, is there a way to do likewise?

One crude solution would be to load a package but not import anything, then write a bunch of foo <- pkg::foo assignments to manually import, but I can't see how to just load without importing in the first place.

Upvotes: 4

Views: 273

Answers (2)

Josh O&#39;Brien
Josh O&#39;Brien

Reputation: 162451

If you find yourself repeatedly wanting to use the same few functions from a package, the cleanest solution might be to create and load a package containing just those functions .

## Set up package source directory
dummy <- ""  ## Need one object with which to initiate package skeleton
package.skeleton("dummy", "dummy")

## Clean up the man subdirectory
lapply(dir("dummy/man", full.names=TRUE), file.remove)

## Use NAMESPACE to pull in the functions you want
funs <- c("aaply", "ddply", "adply")
cat(paste0("importFrom(plyr, ", paste(funs, collapse=", "), ")"),
    paste0("export(", paste(funs, collapse=", "), ")"),
    file = "dummy/NAMESPACE",
    sep = "\n")

## install the package
library(devtools)
install("dummy")

## Confirm that it worked
library(dummy)
ls(2)
# [1] "aaply" "adply" "ddply"
environment(aaply)
# <environment: namespace:plyr>
aaply(matrix(1:9, ncol=3), 2, mean)
# 1 2 3 
# 2 5 8

Upvotes: 4

Ken Williams
Ken Williams

Reputation: 24005

Perhaps all I need to do is this (giving it real names instead of foo so it can be run)?

loadNamespace('zoo')
rollmean <- zoo::rollmean
rollmean.default <- zoo::rollmean.default

Any comments about pitfalls of doing so? I haven't used loadNamespace() before.

Upvotes: 1

Related Questions