获取R包中的函数和对象列表—科研工具箱

请关注公众号【叨客学习资料】 在使用网站的过程中有疑问,请来公众号进行反馈哦

问题

你想知道包里有什么。

方案

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

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\"

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

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
      }
      
      
    }
  }
  return(objectlist)
  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\")
}

ggplot2包作为示例测试:

showPackageContents(\"package:ggplot2\")
package:ggplot2
Primitive functions:
================================================
Non-primitive functions:
aes aes_ aes_all aes_auto aes_q aes_string after_scale after_stat alpha annotate annotation_custom annotation_logticks annotation_map annotation_raster arrow as_label as_labeller autolayer autoplot benchplot binned_scale borders calc_element combine_vars continuous_scale coord_cartesian coord_equal coord_fixed coord_flip coord_map coord_munch coord_polar coord_quickmap coord_sf coord_trans cut_interval cut_number cut_width derive discrete_scale draw_key_abline draw_key_blank draw_key_boxplot draw_key_crossbar draw_key_dotplot draw_key_label draw_key_path draw_key_point draw_key_pointrange draw_key_polygon draw_key_rect draw_key_smooth draw_key_text draw_key_timeseries draw_key_vline draw_key_vpath dup_axis el_def element_blank element_grob element_line element_rect element_render element_text enexpr enexprs enquo enquos ensym ensyms expand_limits expand_scale expansion expr facet_grid facet_null facet_wrap find_panel flip_data flipped_names fortify geom_abline geom_area geom_bar geom_bin_2d geom_bin2d geom_blank geom_boxplot geom_col geom_contour geom_contour_filled geom_count geom_crossbar geom_curve geom_density geom_density_2d geom_density_2d_filled geom_density2d geom_density2d_filled geom_dotplot geom_errorbar geom_errorbarh geom_freqpoly geom_function geom_hex geom_histogram geom_hline geom_jitter geom_label geom_line geom_linerange geom_map geom_path geom_point geom_pointrange geom_polygon geom_qq geom_qq_line geom_quantile geom_raster geom_rect geom_ribbon geom_rug geom_segment geom_sf geom_sf_label geom_sf_text geom_smooth geom_spoke geom_step geom_text geom_tile geom_violin geom_vline get_alt_text get_element_tree gg_dep ggplot ggplot_add ggplot_build ggplot_gtable ggplotGrob ggproto ggproto_parent ggsave ggtitle guide_axis guide_bins guide_colorbar guide_colorsteps guide_colourbar guide_coloursteps guide_gengrob guide_geom guide_legend guide_merge guide_none guide_train guide_transform guides has_flipped_aes is.Coord is.facet is.ggplot is.ggproto is.theme label_both label_bquote label_context label_parsed label_value label_wrap_gen labeller labs last_plot layer layer_data layer_grob layer_scales layer_sf lims map_data margin max_height max_width mean_cl_boot mean_cl_normal mean_sdl mean_se median_hilow merge_element panel_cols panel_rows position_dodge position_dodge2 position_fill position_identity position_jitter position_jitterdodge position_nudge position_stack qplot quickplot quo quo_name quos register_theme_elements rel remove_missing render_axes render_strips reset_theme_settings resolution scale_alpha scale_alpha_binned scale_alpha_continuous scale_alpha_date scale_alpha_datetime scale_alpha_discrete scale_alpha_identity scale_alpha_manual scale_alpha_ordinal scale_color_binned scale_color_brewer scale_color_continuous scale_color_date scale_color_datetime scale_color_discrete scale_color_distiller scale_color_fermenter scale_color_gradient scale_color_gradient2 scale_color_gradientn scale_color_grey scale_color_hue scale_color_identity scale_color_manual scale_color_ordinal scale_color_steps scale_color_steps2 scale_color_stepsn scale_color_viridis_b scale_color_viridis_c scale_color_viridis_d scale_colour_binned scale_colour_brewer scale_colour_continuous scale_colour_date scale_colour_datetime scale_colour_discrete scale_colour_distiller scale_colour_fermenter scale_colour_gradient scale_colour_gradient2 scale_colour_gradientn scale_colour_grey scale_colour_hue scale_colour_identity scale_colour_manual scale_colour_ordinal scale_colour_steps scale_colour_steps2 scale_colour_stepsn scale_colour_viridis_b scale_colour_viridis_c scale_colour_viridis_d scale_continuous_identity scale_discrete_identity scale_discrete_manual scale_fill_binned scale_fill_brewer scale_fill_continuous scale_fill_date scale_fill_datetime scale_fill_discrete scale_fill_distiller scale_fill_fermenter scale_fill_gradient scale_fill_gradient2 scale_fill_gradientn scale_fill_grey scale_fill_hue scale_fill_identity scale_fill_manual scale_fill_ordinal scale_fill_steps scale_fill_steps2 scale_fill_stepsn scale_fill_viridis_b scale_fill_viridis_c scale_fill_viridis_d scale_linetype scale_linetype_binned scale_linetype_continuous scale_linetype_discrete scale_linetype_identity scale_linetype_manual scale_radius scale_shape scale_shape_binned scale_shape_continuous scale_shape_discrete scale_shape_identity scale_shape_manual scale_shape_ordinal scale_size scale_size_area scale_size_binned scale_size_binned_area scale_size_continuous scale_size_date scale_size_datetime scale_size_discrete scale_size_identity scale_size_manual scale_size_ordinal scale_type scale_x_binned scale_x_continuous scale_x_date scale_x_datetime scale_x_discrete scale_x_log10 scale_x_reverse scale_x_sqrt scale_x_time scale_y_binned scale_y_continuous scale_y_date scale_y_datetime scale_y_discrete scale_y_log10 scale_y_reverse scale_y_sqrt scale_y_time sec_axis set_last_plot sf_transform_xy should_stop stage standardise_aes_names stat stat_bin stat_bin_2d stat_bin_hex stat_bin2d stat_binhex stat_boxplot stat_contour stat_contour_filled stat_count stat_density stat_density_2d stat_density_2d_filled stat_density2d stat_density2d_filled stat_ecdf stat_ellipse stat_function stat_identity stat_qq stat_qq_line stat_quantile stat_sf stat_sf_coordinates stat_smooth stat_spoke stat_sum stat_summary stat_summary_2d stat_summary_bin stat_summary_hex stat_summary2d stat_unique stat_ydensity summarise_coord summarise_layers summarise_layout sym syms theme theme_bw theme_classic theme_dark theme_get theme_gray theme_grey theme_light theme_linedraw theme_minimal theme_replace theme_set theme_test theme_update theme_void transform_position unit update_geom_defaults update_labels update_stat_defaults vars waiver wrap_dims xlab xlim ylab ylim zeroGrob
================================================
Constants:
================================================
Objects:
AxisSecondary Coord CoordCartesian CoordFixed CoordFlip CoordMap CoordPolar CoordQuickmap CoordSf CoordTrans diamonds economics economics_long Facet FacetGrid FacetNull FacetWrap faithfuld Geom GeomAbline GeomAnnotationMap GeomArea GeomBar GeomBlank GeomBoxplot GeomCol GeomContour GeomContourFilled GeomCrossbar GeomCurve GeomCustomAnn GeomDensity GeomDensity2d GeomDensity2dFilled GeomDotplot GeomErrorbar GeomErrorbarh GeomFunction GeomHex GeomHline GeomLabel GeomLine GeomLinerange GeomLogticks GeomMap GeomPath GeomPoint GeomPointrange GeomPolygon GeomQuantile GeomRaster GeomRasterAnn GeomRect GeomRibbon GeomRug GeomSegment GeomSf GeomSmooth GeomSpoke GeomStep GeomText GeomTile GeomViolin GeomVline label_both label_context label_parsed label_value Layout luv_colours midwest mpg msleep Position PositionDodge PositionDodge2 PositionFill PositionIdentity PositionJitter PositionJitterdodge PositionNudge PositionStack presidential Scale ScaleBinned ScaleBinnedPosition ScaleContinuous ScaleContinuousDate ScaleContinuousDatetime ScaleContinuousIdentity ScaleContinuousPosition ScaleDiscrete ScaleDiscreteIdentity ScaleDiscretePosition seals Stat StatBin StatBin2d StatBindot StatBinhex StatBoxplot StatContour StatContourFilled StatCount StatDensity StatDensity2d StatDensity2dFilled StatEcdf StatEllipse StatFunction StatIdentity StatQq StatQqLine StatQuantile StatSf StatSfCoordinates StatSmooth StatSum StatSummary StatSummary2d StatSummaryBin StatSummaryHex StatUnique StatYdensity txhousing

ggsci包作为示例测试:

aaaaa<-showPackageContents(\"package:ggsci\")
package:ggsci
================================================
Primitive functions: 


================================================
Non-primitive functions: 
pal_aaas pal_d3 pal_futurama pal_gsea pal_igv pal_jama pal_jco pal_lancet pal_locuszoom pal_material pal_nejm pal_npg pal_rickandmorty pal_simpsons pal_startrek pal_tron pal_uchicago pal_ucscgb rgb_gsea rgb_material scale_color_aaas scale_color_d3 scale_color_futurama scale_color_gsea scale_color_igv scale_color_jama scale_color_jco scale_color_lancet scale_color_locuszoom scale_color_material scale_color_nejm scale_color_npg scale_color_rickandmorty scale_color_simpsons scale_color_startrek scale_color_tron scale_color_uchicago scale_color_ucscgb scale_colour_aaas scale_colour_d3 scale_colour_futurama scale_colour_gsea scale_colour_igv scale_colour_jama scale_colour_jco scale_colour_lancet scale_colour_locuszoom scale_colour_material scale_colour_nejm scale_colour_npg scale_colour_rickandmorty scale_colour_simpsons scale_colour_startrek scale_colour_tron scale_colour_uchicago scale_colour_ucscgb scale_fill_aaas scale_fill_d3 scale_fill_futurama scale_fill_gsea scale_fill_igv scale_fill_jama scale_fill_jco scale_fill_lancet scale_fill_locuszoom scale_fill_material scale_fill_nejm scale_fill_npg scale_fill_rickandmorty scale_fill_simpsons scale_fill_startrek scale_fill_tron scale_fill_uchicago scale_fill_ucscgb

================================================
Constants: 


================================================
Objects: 
图片[1]-获取R包中的函数和对象列表—科研工具箱-叨客学习资料网

本文参考自微信公众号 – 优雅R(elegant-r),作者:王诗翔

© 版权声明
THE END
喜欢就支持一下吧
点赞0 分享
评论 抢沙发
头像
请输入有效评论哦,肆意灌水或者乱打评论是不会通过的,会影响您评论后获得资源哦~~
提交
头像

昵称

取消
昵称表情

    暂无评论内容