「R」获取R包中的函数和对象列表

2020-07-03 12:12:10 浏览数 (1)

问题

你想知道包里有什么。

方案

在一个新的 R 会话中使用 search() 可以查看默认加载的包。

代码语言:javascript复制
search()
#>  [1] ".GlobalEnv"        "package:ellipse"  
#>  [3] "package:Cairo"     "package:grid"     
#>  [5] "package:dplyr"     "package:scales"   
#>  [7] "package:Rmisc"     "package:plyr"     
#>  [9] "package:lattice"   "package:reshape2" 
#> [11] "package:ggplot2"   "package:car"      
#> [13] "package:carData"   "package:sm"       
#> [15] "package:stats"     "package:graphics" 
#> [17] "package:grDevices" "package:utils"    
#> [19] "package:datasets"  "package:methods"  
#> [21] "Autoloads"         "package:base"

以下提供的函数能够列出包中的函数和对象。

代码语言:javascript复制
showPackageContents <- function(packageName) {
  
  # 获取特定包所有内容的列表
  funlist <- objects(packageName)
  
  # 移除不以字母开头的东西
  idx <- grep("^[a-zA-Z][a-zA-Z0-9._]*", funlist)
  funlist <- funlist[idx]
  
  # 移除包含箭头 <- 的东西
  idx <- grep("<-", funlist)
  if (length(idx) != 0) 
    funlist <- funlist[-idx]
  
  # 创建一个数据框保存数据
  objectlist <- data.frame(name = funlist, primitive = FALSE, 
    func = FALSE, object = FALSE, constant = FALSE, 
    stringsAsFactors = F)
  
  for (i in 1:nrow(objectlist)) {
    fname <- objectlist$name[i]
    if (exists(fname)) {
      obj <- get(fname)
      if (is.primitive(obj)) {
        objectlist$primitive[i] <- TRUE
      }
      if (is.function(obj)) {
        objectlist$func[i] <- TRUE
      }
      if (is.object(obj)) {
        objectlist$object[i] <- TRUE
      }
      
      # 我认为这些基本是常量
      if (is.vector(obj)) {
        objectlist$constant[i] <- TRUE
      }
      
      
    }
  }
  
  cat(packageName)
  
  cat("n================================================n")
  cat("Primitive functions: n")
  cat(objectlist$name[objectlist$primitive])
  cat("n")
  
  cat("n================================================n")
  cat("Non-primitive functions: n")
  cat(objectlist$name[objectlist$func & !objectlist$primitive])
  cat("n")
  
  cat("n================================================n")
  cat("Constants: n")
  cat(objectlist$name[objectlist$constant])
  cat("n")
  
  cat("n================================================n")
  cat("Objects: n")
  cat(objectlist$name[objectlist$object])
  cat("n")
}

base 包作为示例测试:

代码语言:javascript复制
showPackageContents("package:base")
#> package:base
#> ================================================
#> Primitive functions: 
#> abs acos acosh all any anyNA Arg as.call as.character as.complex as.double as.environment as.integer as.logical as.numeric as.raw asin asinh atan atanh attr attributes baseenv break browser call ceiling class Conj cos cosh cospi cummax cummin cumprod cumsum digamma dim dimnames emptyenv enc2native enc2utf8 exp expm1 expression floor for forceAndCall function gamma gc.time globalenv if Im interactive invisible is.array is.atomic is.call is.character is.complex is.double is.environment is.expression is.finite is.function is.infinite is.integer is.language is.list is.logical is.matrix is.na is.name is.nan is.null is.numeric is.object is.pairlist is.raw is.recursive is.single is.symbol isS4 lazyLoadDBfetch length lgamma list log log10 log1p log2 max min missing Mod names nargs next nzchar oldClass on.exit pos.to.env proc.time prod quote range Re rep repeat retracemem return round seq_along seq_len seq.int sign signif sin sinh sinpi sqrt standardGeneric substitute sum switch tan tanh tanpi tracemem trigamma trunc unclass untracemem UseMethod while xtfrm
#> 
#> ================================================
#> Non-primitive functions: 
/*
* 提示:该行代码过长,系统自动注释不进行高亮。一键复制会移除系统注释 
* #> abbreviate addNA addTaskCallback agrep agrepl alist all.equal all.equal.character all.equal.default all.equal.environment all.equal.envRefClass all.equal.factor all.equal.formula all.equal.language all.equal.list all.equal.numeric all.equal.POSIXt all.equal.raw all.names all.vars allowInterrupts anyDuplicated anyDuplicated.array anyDuplicated.data.frame anyDuplicated.default anyDuplicated.matrix anyNA.numeric_version anyNA.POSIXlt aperm aperm.default aperm.table append apply args array arrayInd as.array as.array.default as.character.condition as.character.Date as.character.default as.character.error as.character.factor as.character.hexmode as.character.numeric_version as.character.octmode as.character.POSIXt as.character.srcref as.data.frame as.data.frame.array as.data.frame.AsIs as.data.frame.character as.data.frame.complex as.data.frame.data.frame as.data.frame.Date as.data.frame.default as.data.frame.difftime as.data.frame.factor as.data.frame.integer as.data.frame.list as.data.frame.logical as.data.frame.matrix as.data.frame.model.matrix as.data.frame.noquote as.data.frame.numeric as.data.frame.numeric_version as.data.frame.ordered as.data.frame.POSIXct as.data.frame.POSIXlt as.data.frame.raw as.data.frame.table as.data.frame.ts as.data.frame.vector as.Date as.Date.character as.Date.default as.Date.factor as.Date.numeric as.Date.POSIXct as.Date.POSIXlt as.difftime as.double.difftime as.double.POSIXlt as.expression as.expression.default as.factor as.function as.function.default as.hexmode as.list as.list.data.frame as.list.Date as.list.default as.list.environment as.list.factor as.list.function as.list.numeric_version as.list.POSIXct as.list.POSIXlt as.logical.factor as.matrix as.matrix.data.frame as.matrix.default as.matrix.noquote as.matrix.POSIXlt as.name as.null as.null.default as.numeric_version as.octmode as.ordered as.package_version as.pairlist as.POSIXct as.POSIXct.Date as.POSIXct.default as.POSIXct.numeric as.POSIXct.POSIXlt as.POSIXlt as.POSIXlt.character as.POSIXlt.Date as.POSIXlt.default as.POSIXlt.factor as.POSIXlt.numeric as.POSIXlt.POSIXct as.qr as.single as.single.default as.symbol as.table as.table.default as.vector as.vector.factor asNamespace asplit asS3 asS4 assign atan2 attach attachNamespace attr.all.equal autoload autoloader backsolve basename besselI besselJ besselK besselY beta bindingIsActive bindingIsLocked bindtextdomain bitwAnd bitwNot bitwOr bitwShiftL bitwShiftR bitwXor body bquote browserCondition browserSetDebug browserText builtins by by.data.frame by.default bzfile c.Date c.difftime c.noquote c.numeric_version c.POSIXct c.POSIXlt c.warnings callCC capabilities casefold cat cbind cbind.data.frame char.expand character charmatch charToRaw chartr check_tzones chkDots chol chol.default chol2inv choose clearPushBack close close.connection close.srcfile close.srcfilealias closeAllConnections col colMeans colnames colSums commandArgs comment complex computeRestarts conditionCall conditionCall.condition conditionMessage conditionMessage.condition conflictRules conflicts contributors crossprod Cstack_info curlGetHeaders cut cut.Date cut.default cut.POSIXt data.class data.frame data.matrix date debug debuggingState debugonce default.stringsAsFactors delayedAssign deparse det detach determinant determinant.matrix dget diag diff diff.Date diff.default diff.difftime diff.POSIXt difftime dim.data.frame dimnames.data.frame dir dir.create dir.exists dirname do.call dontCheck double dput dQuote drop droplevels droplevels.data.frame droplevels.factor dump duplicated duplicated.array duplicated.data.frame duplicated.default duplicated.matrix duplicated.numeric_version duplicated.POSIXlt duplicated.warnings dyn.load dyn.unload dynGet eapply eigen encodeString Encoding endsWith enquote env.profile environment environmentIsLocked environmentName errorCondition eval eval.parent evalq exists expand.grid extSoftVersion factor factorial fifo file file.access file.append file.choose file.copy file.create file.exists file.info file.link file.mode file.mtime file.path file.remove file.rename file.show file.size file.symlink Filter Find find.package findInterval findPackageEnv findRestart flush flush.connection force formals format format.AsIs format.data.frame format.Date format.default format.difftime format.factor format.hexmode format.info format.libraryIQR format.numeric_version format.octmode format.packageInfo format.POSIXct format.POSIXlt format.pval format.summaryDefault formatC formatDL forwardsolve gc gcinfo gctorture gctorture2 get get0 getAllConnections getCallingDLL getCallingDLLe getConnection getDLLRegisteredRoutines getDLLRegisteredRoutines.character getDLLRegisteredRoutines.DLLInfo getElement geterrmessage getExportedValue getHook getLoadedDLLs getNamespace getNamespaceExports getNamespaceImports getNamespaceInfo getNamespaceName getNamespaceUsers getNamespaceVersion getNativeSymbolInfo getOption getRversion getSrcLines getTaskCallbackNames gettext gettextf getwd gl gregexpr grep grepl grepRaw grouping gsub gzcon gzfile I iconv iconvlist icuGetCollate icuSetCollate identical identity ifelse importIntoEnv inherits integer interaction intersect intToBits intToUtf8 inverse.rle invokeRestart invokeRestartInteractively is.data.frame is.element is.factor is.loaded is.na.data.frame is.na.numeric_version is.na.POSIXlt is.numeric_version is.numeric.Date is.numeric.difftime is.numeric.POSIXt is.ordered is.package_version is.primitive is.qr is.R is.table is.unsorted is.vector isatty isBaseNamespace isdebugged isFALSE isIncomplete isNamespace isNamespaceLoaded ISOdate ISOdatetime isOpen isRestart isSeekable isSymmetric isSymmetric.matrix isTRUE jitter julian julian.Date julian.POSIXt kappa kappa.default kappa.lm kappa.qr kronecker l10n_info La_library La_version La.svd labels.default lapply lazyLoad lazyLoadDBexec lbeta lchoose length.POSIXlt lengths levels levels.default lfactorial libcurlVersion library library.dynam library.dynam.unload licence license list.dirs list.files list2env load loadedNamespaces loadingNamespaceInfo loadNamespace local lockBinding lockEnvironment logb logical lower.tri ls make.names make.unique makeActiveBinding Map mapply margin.table mat.or.vec match match.arg match.call match.fun Math.data.frame Math.Date Math.difftime Math.factor Math.POSIXt matrix max.col mean mean.Date mean.default mean.difftime mean.POSIXct mean.POSIXlt mem.limits mem.maxNSize mem.maxVSize memCompress memDecompress memory.profile merge merge.data.frame merge.default message mget mode months months.Date months.POSIXt names.POSIXlt namespaceExport namespaceImport namespaceImportClasses namespaceImportFrom namespaceImportMethods nchar ncol NCOL Negate new.env NextMethod ngettext nlevels noquote norm normalizePath nrow NROW nullfile numeric numeric_version objects OlsonNames open open.connection open.srcfile open.srcfilealias open.srcfilecopy Ops.data.frame Ops.Date Ops.difftime Ops.factor Ops.numeric_version Ops.ordered Ops.POSIXt options order ordered outer package_version packageEvent packageHasNamespace packageNotFoundError packageStartupMessage packBits pairlist parent.env parent.frame parse parseNamespaceFile paste paste0 path.expand path.package pcre_config pipe pmatch pmax pmax.int pmin pmin.int polyroot pretty pretty.default prettyNum print print.AsIs print.by print.condition print.connection print.data.frame print.Date print.default print.difftime print.Dlist print.DLLInfo print.DLLInfoList print.DLLRegisteredRoutines print.eigen print.factor print.function print.hexmode print.libraryIQR print.listof print.NativeRoutineList print.noquote print.numeric_version print.octmode print.packageInfo print.POSIXct print.POSIXlt print.proc_time print.restart print.rle print.simple.list print.srcfile print.srcref print.summary.table print.summary.warnings print.summaryDefault print.table print.warnings prmatrix prop.table provideDimnames psigamma pushBack pushBackLength q qr qr.coef qr.default qr.fitted qr.Q qr.qty qr.qy qr.R qr.resid qr.solve qr.X quarters quarters.Date quarters.POSIXt quit R_system_version R.home R.Version range.default rank rapply raw rawConnection rawConnectionValue rawShift rawToBits rawToChar rbind rbind.data.frame rcond read.dcf readBin readChar readline readLines readRDS readRenviron Recall Reduce reg.finalizer regexec regexpr registerS3method registerS3methods regmatches remove removeTaskCallback rep_len rep.Date rep.factor rep.int rep.numeric_version rep.POSIXct rep.POSIXlt replace replicate require requireNamespace restartDescription restartFormals returnValue rev rev.default rle rm RNGkind RNGversion round.Date round.POSIXt row row.names row.names.data.frame row.names.default rowMeans rownames rowsum rowsum.data.frame rowsum.default rowSums sample sample.int sapply save save.image saveRDS scale scale.default scan search searchpaths seek seek.connection seq seq.Date seq.default seq.POSIXt sequence serialize set.seed setdiff setequal setHook setNamespaceInfo setSessionTimeLimit setTimeLimit setwd showConnections shQuote signalCondition simpleCondition simpleError simpleMessage simpleWarning simplify2array single sink sink.number slice.index socketConnection socketSelect solve solve.default solve.qr sort sort.default sort.int sort.list sort.POSIXlt source split split.data.frame split.Date split.default split.POSIXct sprintf sQuote srcfile srcfilealias srcfilecopy srcref startsWith stderr stdin stdout stop stopifnot storage.mode str2expression str2lang strftime strptime strrep strsplit strtoi strtrim structure strwrap sub subset subset.data.frame subset.default subset.matrix substr substring summary summary.connection summary.data.frame Summary.data.frame summary.Date Summary.Date summary.default Summary.difftime summary.factor Summary.factor summary.matrix Summary.numeric_version Summary.ordered summary.POSIXct Summary.POSIXct summary.POSIXlt Summary.POSIXlt summary.proc_time summary.srcfile summary.srcref summary.table summary.warnings suppressMessages suppressPackageStartupMessages suppressWarnings suspendInterrupts svd sweep sys.call sys.calls Sys.chmod Sys.Date sys.frame sys.frames sys.function Sys.getenv Sys.getlocale Sys.getpid Sys.glob Sys.info sys.load.image Sys.localeconv sys.nframe sys.on.exit sys.parent sys.parents Sys.readlink sys.save.image Sys.setenv Sys.setFileTime Sys.setlocale Sys.sleep sys.source sys.status Sys.time Sys.timezone Sys.umask Sys.unsetenv Sys.which system system.file system.time system2 t.data.frame t.default table tabulate tapply taskCallbackManager tcrossprod tempdir tempfile textConnection textConnectionValue tolower topenv toString toString.default toupper trace traceback tracingState transform transform.data.frame transform.default trimws trunc.Date trunc.POSIXt truncate truncate.connection try tryCatch typeof undebug union unique unique.array unique.data.frame unique.default unique.matrix unique.numeric_version unique.POSIXlt unique.warnings units units.difftime unix.time unlink unlist unloadNamespace unlockBinding unname unserialize unsplit untrace unz upper.tri url utf8ToInt validEnc validUTF8 vapply vector Vectorize warning warningCondition warnings weekdays weekdays.Date weekdays.POSIXt which which.max which.min with with.default withAutoprint withCallingHandlers within within.data.frame within.list withRestarts withVisible write write.dcf writeBin writeChar writeLines xor xpdrows.data.frame xtfrm.AsIs xtfrm.Date xtfrm.default xtfrm.difftime xtfrm.factor xtfrm.numeric_version xtfrm.POSIXct xtfrm.POSIXlt xzfile zapsmall
*/
#> 
#> ================================================
#> Constants: 
#> c F labels letters LETTERS month.abb month.name pi R.version.string t T
#> 
#> ================================================
#> Objects: 
#> kronecker Position R.version version

0 人点赞