سؤال

Is there an easy way to list everything in a package from within R?
For example, if I type foreach::: and hit tab twice, I can see everything that's there.
How else can I get those names of objects?

Note, ls("package:foreach", all.names=TRUE) does not show things like .foreachGlobals

هل كانت مفيدة؟

المحلول

ls("package:foreach", all.names=TRUE) only shows what's attached to the search path, which only includes the objects exported from the namespace. Use ls on the results of getNamespace instead:

ls(getNamespace("foreach"), all.names=TRUE)

نصائح أخرى

A utility that I've been using which I find useful for this (and also gives some other helpful things) such as:

ls(get('.__NAMESPACE__.', envir = asNamespace('ggplot2', base.OK = FALSE),
       inherits = FALSE))
[1] "dynlibs"   "exports"   "imports"   "lazydata"  "path"      "S3methods" "spec"     

to access all exported and internal variables in the NAMESPACE, ie,

ggplot2:::

lsp(ggplot2)

# [1] ".__C__Scales"                     ".__global__"                     
# [3] ".__NAMESPACE__."                  ".__S3MethodsTable__."            
# [5] ".all_aesthetics"                  ".base_to_ggplot"                 
# [7] ".element_tree"                    ".onAttach"                       
# [9] ".packageName"                     ".plot_store" 
# ...

to access only exported, ie,

ggplot2::

lsp(ggplot2, 'exports')

# $exports
# [1] "%+%"                       "%+replace%"               
# [3] "aes"                       "aes_all"                  
# [5] "aes_auto"                  "aes_q"                    
# [7] "aes_string"                "annotate"                 
# [9] "annotation_custom"         "annotation_logticks"    
# ...

for the library path

lsp('ggplot2', 'path')

# $path
# [1] "/Library/Frameworks/R.framework/Versions/3.1/Resources/library/ggplot2"

for data included in packages

lsp('ggplot2', 'lazydata')

# $lazydata
# [1] "diamonds"     "economics"    "midwest"      "movies"       "mpg"         
# [6] "msleep"       "presidential" "seals"  

for S3 methods

lsp('ggplot2', 'S3methods')

# $S3methods
# [,1]                         [,2]                       [,3]                              
# [1,] "+"                     "gg"                       "+.gg"                            
# [2,] "["                     "uneval"                   "[.uneval"                        
# [3,] "as.character"          "uneval"                   "as.character.uneval"             
# [4,] "autoplot"              "default"                  "autoplot.default"                
# [5,] "coord_aspect"          "default"                  "coord_aspect.default"            
# [6,] "coord_aspect"          "fixed"                    "coord_aspect.fixed"              
# [7,] "coord_aspect"          "map"                      "coord_aspect.map"                
# [8,] "coord_aspect"          "polar"                    "coord_aspect.polar"              
# [9,] "coord_aspect"          "quickmap"                 "coord_aspect.quickmap" 
# ...

to see everything

lsp('ggplot2')

# pages and pages

code:

lsp <- function(package, what, pattern) {
  if (!is.character(substitute(package)))
    package <- deparse(substitute(package))
  ns <- asNamespace(package)
  if (missing(pattern))
    pattern <- '.*'

  ## base package does not have NAMESPACE
  if (isBaseNamespace(ns)) {
    res <- ls(.BaseNamespaceEnv, all.names = TRUE)
    return(res[grep(pattern, res, perl = TRUE, ignore.case = TRUE)])
  } else {
    ## for non base packages
    if (exists('.__NAMESPACE__.', envir = ns, inherits = FALSE)) {
      wh <- get('.__NAMESPACE__.', inherits = FALSE,
                envir = asNamespace(package, base.OK = FALSE))
      what <- if (missing(what)) 'all'
      else if ('?' %in% what) return(ls(wh)) 
      else ls(wh)[pmatch(what[1], ls(wh))]
      if (!is.null(what) && !any(what %in% c('all', ls(wh))))
        stop('\'what\' should be one of ',
             paste0(shQuote(ls(wh)), collapse = ', '),
             ', or \'all\'', domain = NA)
      res <- sapply(ls(wh), function(x) getNamespaceInfo(ns, x))
      res <- rapply(res, ls, classes = 'environment',
                    how = 'replace', all.names = TRUE)
      if (is.null(what))
        return(res[grep(pattern, res, perl = TRUE, ignore.case = TRUE)])
      if (what %in% 'all') {
        res <- ls(getNamespace(package), all.names = TRUE)
        return(res[grep(pattern, res, perl = TRUE, ignore.case = TRUE)])
      }
      if (any(what %in% ls(wh))) {
        res <- res[[what]]
        return(res[grep(pattern, res, perl = TRUE, ignore.case = TRUE)])
      }
    } else stop(sprintf('no NAMESPACE file found for package %s', package))
  }
}

I also like it because it shows how useful rapply can be :}

Revolution R Enterprise (free for Academic use) is an editor/debugger/GUI for R which has an 'Object Browser' window open on startup by default. Clicking on a package allows you to see all of its contents including classes and environments. I find this quite helpful.

I know this is an older question, but I recently created a script that works well for getting this information. It will take a vector of package names get the following information for every function within each package. The package name, the function name, the str() for the function, and the description text from the help file for each function. Code is below in case if anyone is interested.

available.packages <- installed.packages()
suppressMessages(if(!"XML" %in% available.packages) install.packages("XML",repos = "https://cran.cnr.berkeley.edu/"))
library(XML)

# Function to get data from help console
help_console <- function(topic, format=c("text", "html", "latex", "Rd"),
                         lines=NULL, before=NULL, after=NULL, pkg) {  
  format=match.arg(format)
  if (!is.character(topic)) topic <- deparse(substitute(topic))

  helpfile <- tryCatch({
    helpfile <- utils:::.getHelpFile(help(topic, package = as.character(pkg)))
  }, error = function(err) {
    helpfile <- NA
  }) 

  if(!is.na(helpfile[1]))
    {hs <- capture.output(switch(format, 
                                 text=tools:::Rd2txt(helpfile),
                                 html=tools:::Rd2HTML(helpfile),
                                 latex=tools:::Rd2latex(helpfile),
                                 Rd=tools:::prepare_Rd(helpfile)))

     if(!is.null(lines)) hs <- hs[lines]
     hs <- c(before, hs, after)
     html <- paste(hs, sep="\n", collapse = "")
  } else{
    html <- NA
  }

  return(html)
}

# Function to retrieve information on functions within a package
get.funcs <- function(pkg){
  if(pkg %in% available.packages){
    print(pkg)
    require(pkg, character.only = TRUE)

    df <- as.data.frame(as.vector(lsf.str(paste0("package:", pkg))), stringsAsFactors = FALSE)
    colnames(df) <- "function.name"

    df$usage <- sapply(df$function.name, function(x) capture.output(str(get(x)))[1])
    df$package <- pkg

    df$description <- mapply(function(x,y) {
                             html <- help_console(x, "html", lines = 1:25, before = "", after = "", pkg = y)
                             if(!is.na(html)){
                               doc <- htmlParse(html, asText = TRUE)
                               plain.text <- xpathSApply(doc, "//p", xmlValue)[1]
                             } else{
                               plain.text <- NA
                             }
                             },
                             df$function.name,
                             df$package)

    return(df[,c("package","function.name","usage","description")])
  } else{
    print(paste(pkg, "- has not been installed and cannot be processed!"))
    return(NULL)
  }
}


# Create a vector of packages to process
packages <- c("base","dplyr","lubridate","plyr","readr","readxl","reshape2","RODBC","stringr","tidyr","XLConnect","xlsx","XML","zoo")

# Create a list of dataframes containing package information
ldf <- lapply(packages, get.funcs)

# Combine all dataframes in the list to a single dataframe
df <- do.call(rbind, ldf)
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top