20

有没有一种简单的方法可以从 R 中列出包中的所有内容?
例如,如果我键入foreach:::并点击tab两次,我可以看到那里的所有内容。
我还能如何获得这些对象的名称?

注意,ls("package:foreach", all.names=TRUE)不显示类似的东西.foreachGlobals

4

4 回答 4

29

ls("package:foreach", all.names=TRUE)仅显示附加到搜索路径的内容,其中仅包括从命名空间导出的对象。ls在结果上使用getNamespace

ls(getNamespace("foreach"), all.names=TRUE)
于 2012-08-24T19:26:41.390 回答
7

我一直在使用的一个实用程序,我发现它对此很有用(并且还提供了一些其他有用的东西),例如:

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

访问 NAMESPACE 中的所有导出和内部变量,即

ggplot2:::

lsp(ggplot2)

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

仅访问导出的,即

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"    
# ...

对于库路径

lsp('ggplot2', 'path')

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

对于包中包含的数据

lsp('ggplot2', 'lazydata')

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

对于 S3 方法

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" 
# ...

看到一切

lsp('ggplot2')

# pages and pages

代码:

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))
  }
}

我也喜欢它,因为它展示了它的用处rapply:}

于 2014-07-16T18:43:58.097 回答
1

Revolution R Enterprise(免费供学术使用)是 R 的编辑器/调试器/GUI,默认情况下在启动时打开“对象浏览器”窗口。单击一个包可以查看其所有内容,包括类和环境。我觉得这很有帮助。

于 2012-08-27T03:24:20.813 回答
0

我知道这是一个较老的问题,但我最近创建了一个脚本,可以很好地获取这些信息。它需要一个包名称向量来获取每个包中每个函数的以下信息。包名称、函数名称、函数的 str() 以及每个函数的帮助文件中的描述文本。如果有人感兴趣,代码如下。

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)
于 2017-06-26T17:19:03.303 回答