4

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.

Ken Williams
  • 22,756
  • 10
  • 85
  • 147
  • Maybe some hints in the discussions here: http://stackoverflow.com/questions/6254744/ ? But, what's your objection to loading packages? If there are a couple functions you plan to use a lot, then why not manually import them once and build them into your default environment. – Carl Witthoft Apr 30 '13 at 14:50
  • Loading packages is fine - I just don't want to *import* everything, especially when there are conflicts. I'd rather just import the things I know I'm going to use. I've been burned by unexpected imports before, e.g. when a new version of a package adds an import that didn't formerly exist. – Ken Williams Apr 30 '13 at 15:19

2 Answers2

4

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
Josh O'Brien
  • 159,210
  • 26
  • 366
  • 455
1

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.

Ken Williams
  • 22,756
  • 10
  • 85
  • 147
  • 1
    If you go this route, you don't even need the `loadNamespace()` call. – Josh O'Brien Apr 30 '13 at 16:44
  • Nope, I don't think so. (If you find differently after trying it out, please let me know!) – Josh O'Brien Apr 30 '13 at 17:25
  • 1
    Wow, that's crazy. I had no idea the `::` syntax triggered an auto-load of the code. The documentation confirms it too: "The namespace will be loaded if it was not loaded before the call, but the package will not be attached to the search path." – Ken Williams Apr 30 '13 at 19:37