class: center, middle, inverse, title-slide .title[ # Environments ] .subtitle[ ## Mini-Lecture 11 ] .author[ ### Albert Y. Kim ] .date[ ###
SDS 270
2022-10-27
] --- class: center, inverse, middle # Environments --- ## Types of environments .pull-left[ What I want you to focus on: - 7.4.1: Package environments - 7.4.3: Namespace environments ] -- .pull-right[ Less important for us right now: - 7.2.4: Super assignment - 7.3: Recursing over environments - 7.5: Call stacks - 7.6: Environments as data structures ] --- ## 7.4: [Four Special Environments](https://adv-r.hadley.nz/environments.html#special-environments) 1) **Package** environments: objects provided by the package ```r library(rlang) pkg_env("stats") ``` ``` ## <environment: package:stats> ## attr(,"name") ## [1] "package:stats" ## attr(,"path") ## [1] "/Library/Frameworks/R.framework/Versions/4.2/Resources/library/stats" ``` 2) **Execution** environments: where the function is executed --- ## 7.4: [Four Special Environments](https://adv-r.hadley.nz/environments.html#special-environments) 3) **Namespace** environments: what is available to the function ```r ns_env(stats::sd) ``` ``` ## <environment: namespace:stats> ``` 4) **Function** environments: where the function is defined ```r fn_env(stats::sd) ``` ``` ## <environment: namespace:stats> ``` --- ## Package environment for `stats` ```r pkg_env("stats") %>% env_names() ``` ``` ## [1] "confint.default" "mahalanobis" "optimize" ## [4] "hat" "Box.test" "reorder" ## [7] "phyper" "ar.mle" "rhyper" ## [10] "contr.SAS" "na.exclude" "qgeom" ## [13] "is.ts" "plogis" "drop.terms" ## [16] "rlogis" "convolve" "ts.intersect" ## [19] "KalmanSmooth" "ts.union" "smoothEnds" ## [22] "is.tskernel" "as.formula" "dexp" ## [25] "inverse.gaussian" "na.contiguous" "line" ## [28] "dgeom" "qbirthday" "confint.lm" ## [31] "cophenetic" "var.test" "diffinv" ## [34] "ar" "dummy.coef" "cooks.distance" ## [37] "density" "ptukey" "as.dist" ## [40] "drop1" "rbeta" "fligner.test" ## [43] "naprint" "qqnorm" "is.stepfun" ## [46] "lsfit" "mad" "qqplot" ## [49] "shapiro.test" "eff.aovlist" "runif" ## [52] "isoreg" "profile" "is.leaf" ## [55] "dchisq" "contr.poly" "stepfun" ## [58] "quasipoisson" "na.omit" "pnbinom" ## [61] "ppois" "model.matrix.default" "family" ## [64] "plot.ecdf" "cor.test" "pchisq" ## [67] "rchisq" "na.fail" "heatmap" ## [70] "rmultinom" "qweibull" "power.t.test" ## [73] "complete.cases" "loess.control" "qnbinom" ## [76] "df" "tsp<-" "rnorm" ## [79] "addmargins" "asOneSidedFormula" "Pair" ## [82] "nlm" "covratio" "C" ## [85] "as.stepfun" "D" "ar.burg" ## [88] "cov2cor" "pgeom" "chisq.test" ## [91] "p.adjust" "nls" "integrate" ## [94] "fivenum" "weighted.mean" "rweibull" ## [97] "qqline" "as.dendrogram" "runmed" ## [100] "aov" "dt" "influence" ## [103] "rnbinom" "coefficients" "tsp" ## [106] "dfbeta" "hasTsp" "dbinom" ## [109] "scatter.smooth" "wilcox.test" "start" ## [112] "delete.response" "qsignrank" "is.mts" ## [115] ".getXlevels" "BIC" "ks.test" ## [118] ".nknots.smspl" "order.dendrogram" "SSD" ## [121] "HoltWinters" "qbeta" "pbinom" ## [124] "effects" "rbinom" "monthplot" ## [127] "acf2AR" "splinefunH" "splinefun" ## [130] "qunif" "nls.control" "dbeta" ## [133] "influence.measures" "as.ts" "prop.trend.test" ## [136] "get_all_vars" "summary.glm" "preplot" ## [139] "mood.test" "dunif" "vcov" ## [142] "glm.control" "ar.ols" "qgamma" ## [145] "dendrapply" "arima0.diag" "dnbinom" ## [148] "qnorm" "contrasts<-" "SSbiexp" ## [151] "poisson.test" "add.scope" "dlnorm" ## [154] "makeARIMA" "plot.spec.phase" "tsSmooth" ## [157] "dnorm" "nobs" "knots" ## [160] "fitted" "spline" "symnum" ## [163] "prcomp" "friedman.test" "KalmanForecast" ## [166] "frequency" "aggregate.data.frame" "decompose" ## [169] "dsignrank" "pcauchy" "plot.spec.coherency" ## [172] "dist" "SSmicmen" "predict" ## [175] "lag.plot" "plnorm" "write.ftable" ## [178] "factanal" "resid" "rlnorm" ## [181] "qsmirnov" "rstandard" "optim" ## [184] "plot.ts" "glm.fit" "dmultinom" ## [187] "predict.lm" "getCall" "ansari.test" ## [190] "loadings" "NLSstAsymptotic" "window<-" ## [193] "window" "pbeta" "residuals.glm" ## [196] "pairwise.t.test" "mantelhaen.test" "aggregate" ## [199] "qcauchy" "loess.smooth" "extractAIC" ## [202] "predict.glm" "punif" "approxfun" ## [205] "napredict" "weights" "quasibinomial" ## [208] "rsmirnov" "SSweibull" "ave" ## [211] "ARMAacf" "bw.ucv" "estVar" ## [214] "cor" "pbirthday" "update.formula" ## [217] "se.contrast" "alias" "rcauchy" ## [220] "cov" "case.names" "ls.print" ## [223] "nlminb" "TukeyHSD" "hatvalues" ## [226] "contr.sum" "ppoints" "filter" ## [229] "deviance" "KalmanRun" "pnorm" ## [232] "lag" "ar.yw" "lm" ## [235] "r2dtable" "cpgram" "mcnemar.test" ## [238] "NLSstClosestX" "makepredictcall" "NLSstLfAsymptote" ## [241] "simulate" "toeplitz" "SSasympOrig" ## [244] "summary.manova" "model.extract" "qhyper" ## [247] "model.tables" "add1" "SSfol" ## [250] "ts.plot" "SSasymp" "Gamma" ## [253] "termplot" "bartlett.test" "oneway.test" ## [256] "step" "plot.stepfun" "qlogis" ## [259] "df.kernel" "quasi" "coef" ## [262] "promax" "factor.scope" "poisson" ## [265] "embed" "dcauchy" "na.action" ## [268] "rect.hclust" "SSfpl" "bw.bcv" ## [271] "as.hclust" "varimax" "model.offset" ## [274] "df.residual" "nextn" "hclust" ## [277] "smooth.spline" "qtukey" "bw.nrd0" ## [280] "ppr" "pacf" "power.prop.test" ## [283] "pwilcox" "bw.nrd" "rsignrank" ## [286] "quantile" "stl" "AIC" ## [289] "end" "sortedXyData" "lowess" ## [292] "lm.wfit" "pf" "princomp" ## [295] "terms" "lm.influence" "model.frame" ## [298] "qwilcox" "stat.anova" "qchisq" ## [301] "update.default" "model.response" "drop.scope" ## [304] "residuals" "median" "cycle" ## [307] "DF2formula" "constrOptim" "pt" ## [310] "deriv3" "variable.names" "qf" ## [313] "summary.aov" "update" "rwilcox" ## [316] "pairwise.table" "expand.model.frame" "model.matrix.lm" ## [319] "acf" "proj" "bw.SJ" ## [322] "numericDeriv" "uniroot" "ARMAtoMA" ## [325] "ksmooth" "qt" "dffits" ## [328] ".checkMFClasses" "rstudent" "rf" ## [331] "plclust" "manova" "dwilcox" ## [334] ".vcov.aliased" "kernapply" ".MFclass" ## [337] "cutree" "spec.ar" "cmdscale" ## [340] "poly" "dweibull" "optimise" ## [343] "formula" "rt" "sd" ## [346] "loglin" "qbinom" "gaussian" ## [349] "model.matrix" "median.default" "fitted.values" ## [352] "var" "binomial" "arima.sim" ## [355] "logLik" "selfStart" "reformulate" ## [358] "naresid" "StructTS" "interaction.plot" ## [361] "SSlogis" "supsmu" "dgamma" ## [364] "weighted.residuals" "terms.formula" "smooth" ## [367] "kernel" "confint" "mvfft" ## [370] "kruskal.test" "spec.pgram" "glm" ## [373] "ls.diag" "pairwise.wilcox.test" "NLSstRtAsymptote" ## [376] "pgamma" "rpois" "arima" ## [379] "rgamma" "t.test" "biplot" ## [382] "xtabs" "ts" "SSasympOff" ## [385] "is.empty.model" "summary.lm" "dummy.coef.lm" ## [388] "binom.test" "sigma" "prop.test" ## [391] "na.pass" "make.link" "summary.stepfun" ## [394] "reshape" "ftable" "density.default" ## [397] "dfbetas" "contrasts" "psignrank" ## [400] "polym" "model.frame.default" "rgeom" ## [403] "psmirnov" "contr.treatment" "qlnorm" ## [406] "lm.fit" "arima0" "offset" ## [409] "power.anova.test" "loess" "pairwise.prop.test" ## [412] "kmeans" "aggregate.ts" "relevel" ## [415] "spectrum" "model.weights" "rexp" ## [418] ".lm.fit" "printCoefmat" "PP.test" ## [421] "cov.wt" "residuals.lm" "replications" ## [424] "fisher.test" "qexp" "screeplot" ## [427] "contr.helmert" "deltat" "medpolish" ## [430] "pexp" "rWishart" "ccf" ## [433] "time" "anova" "IQR" ## [436] "optimHess" "KalmanLike" "pweibull" ## [439] "read.ftable" "p.adjust.methods" "fft" ## [442] "cancor" "tsdiag" "qpois" ## [445] "SSgompertz" "getInitial" "power" ## [448] "bandwidth.kernel" "approx" "mauchly.test" ## [451] "quade.test" ".preformat.ts" "deriv" ## [454] "spec.taper" "dhyper" "ecdf" ## [457] "dpois" "setNames" "dlogis" ``` --- ## `sd()` function namespaces via `sd` - Note the **environment**! ```r sd ``` ``` ## function (x, na.rm = FALSE) ## sqrt(var(if (is.vector(x) || is.factor(x)) x else as.double(x), ## na.rm = na.rm)) ## <bytecode: 0x7f841ffaf8f0> ## <environment: namespace:stats> ``` -- ```r find("sqrt") ``` ``` ## [1] "package:base" ``` ```r find("var") ``` ``` ## [1] "package:stats" ``` --- ## Namespace environments ```r ns_env("stats") %>% env_parents() ``` ``` ## [[1]] $ <env: imports:stats> ## [[2]] $ <env: namespace:base> ## [[3]] $ <env: global> ``` ```r global_env() %>% env_parents() ``` ``` ## [[1]] $ <env: package:rlang> ## [[2]] $ <env: package:xaringanthemer> ## [[3]] $ <env: package:forcats> ## [[4]] $ <env: package:stringr> ## [[5]] $ <env: package:dplyr> ## [[6]] $ <env: package:purrr> ## [[7]] $ <env: package:readr> ## [[8]] $ <env: package:tidyr> ## [[9]] $ <env: package:tibble> ## [[10]] $ <env: package:ggplot2> ## [[11]] $ <env: package:tidyverse> ## [[12]] $ <env: package:stats> ## [[13]] $ <env: package:graphics> ## [[14]] $ <env: package:grDevices> ## [[15]] $ <env: package:utils> ## [[16]] $ <env: package:datasets> ## [[17]] $ <env: package:methods> ## [[18]] $ <env: Autoloads> ## [[19]] $ <env: package:base> ## [[20]] $ <env: empty> ``` --- class: middle * Package environments (i.e., the search path) control what is available to **users** * Namespace environments control what is available to **developers** * (this will start to make more sense once we start developing packages!) --- ## namespace:macleish - **functions** that the [`macleish` developers created](https://github.com/beanumber/macleish/blob/master/NAMESPACE) - may or may not be exported ```r library(macleish) ``` ``` ## Loading required package: etl ``` ```r macleish_created <- ns_env("macleish") %>% env_names() macleish_created ``` ``` ## [1] ".__global__" "mass_gis" ## [3] "phenocam_image_url_midday" ".packageName" ## [5] "phenocam_info" "phenocam_image_url" ## [7] "phenocam_download" "phenocam_read_monthly_midday_urls" ## [9] "etl_extract.etl_macleish" "phenocam_read_day_urls" ## [11] ".__NAMESPACE__." "macleish_intersect" ## [13] "etl_transform.etl_macleish" ".__S3MethodsTable__." ## [15] "etl_transform_help" ``` --- ## imports:macleish - objects from other packages that `macleish` developers use ```r macleish_imports <- ns_env("macleish") %>% env_parent() %>% env_names() length(macleish_imports) ``` ``` ## [1] 317 ``` ```r macleish_imports ``` ``` ## [1] "tribble" "do" ## [3] "tbl_sum" "is_grouped_df" ## [5] "is.tbl" "sql_escape_ident" ## [7] "sql" "arrange_if" ## [9] "sql_join" "smart_upload" ## [11] "unzip" "group_map" ## [13] "expr" "union_all" ## [15] "src" "matches" ## [17] "anti_join" "db_query_rows" ## [19] "rename_with" "summarize_each_" ## [21] "match_files_by_year_months" "db_desc" ## [23] "tbl_vars" "tbl" ## [25] "group_nest" "enexprs" ## [27] "summarize_if" "transmute_if" ## [29] "type_sum" "count" ## [31] "dplyr_row_slice" "union" ## [33] "funs_" "filter" ## [35] "slice_head" "valid_year_month" ## [37] "write_csv" "arrange" ## [39] "src_postgres" "cur_group" ## [41] "data_frame" "etl_extract" ## [43] "src_df" "db_create_table" ## [45] "any_vars" "db_type" ## [47] "collapse" "dbRunScript" ## [49] "db_rollback" "changes" ## [51] "semi_join" "last" ## [53] "ymd_hms" "group_cols" ## [55] "summarise" "add_tally_" ## [57] "summarize_each" "nest_join" ## [59] "etl_init" "grouped_df" ## [61] "pull" "data_frame_" ## [63] "ensyms" "head" ## [65] "frame_data" "select_" ## [67] "rows_update" "failwith" ## [69] "cur_group_id" "filter_at" ## [71] "glimpse" "rename_" ## [73] "summarise_if" "select_var" ## [75] "sql_set_op" "dim_desc" ## [77] "db_create_index" "rows_delete" ## [79] "setequal" "tbl_nongroup_vars" ## [81] "group_walk" "new_grouped_df" ## [83] "etl_load" "id" ## [85] "summarise_" "enexpr" ## [87] "db_analyze" "na_if" ## [89] "select_vars_" "select_if" ## [91] "db_query_fields" "db_create_indexes" ## [93] "summarise_each" "sql_subquery" ## [95] "cur_column" "db_save_query" ## [97] "src_local" "any_of" ## [99] "slice_" "group_data" ## [101] "as.tbl" "st_transform" ## [103] "first" "dplyr_reconstruct" ## [105] "select_at" "lst_" ## [107] "recode_factor" "db_explain" ## [109] "intersect" "row_number" ## [111] "eval_tbls" "sql_translate_env" ## [113] "rename_if" "etl_create" ## [115] "ident" "rename_all" ## [117] "arrange_all" "read_csv" ## [119] "src_mysql" "summarise_each_" ## [121] "src_sqlite" "add_count" ## [123] "select_all" "ends_with" ## [125] "summarize_all" "if_all" ## [127] "tally_" "db_begin" ## [129] "show_query" "rename_at" ## [131] "etl_cleanup" "n" ## [133] "do_" "bind_rows" ## [135] "as_label" "bind_cols" ## [137] "db_insert_into" "compute" ## [139] "enquo" "full_join" ## [141] "ensym" "cur_data_all" ## [143] "rename_vars" "rowwise" ## [145] "summarise_all" "relocate" ## [147] "db_has_table" "bench_tbls" ## [149] "quo" "extract_date_from_filename" ## [151] "tbl_ptype" "everything" ## [153] "compare_tbls" "distinct" ## [155] "sql_semi_join" "summarize" ## [157] "ntile" "same_src" ## [159] "sym" "min_rank" ## [161] "case_when" "near" ## [163] "group_split" "group_indices" ## [165] "tbl_df" "mutate_all" ## [167] "all_equal" "group_keys" ## [169] "transmute" "select" ## [171] "num_range" "etl_update" ## [173] "all_vars" "groups" ## [175] "mutate_" "as_data_frame" ## [177] "if_any" "group_by_all" ## [179] "slice_max" "explain" ## [181] "all_of" "is.etl" ## [183] "cume_dist" "cumall" ## [185] "db_data_type" "mutate_each" ## [187] "create_etl_package" "contains" ## [189] "tibble" "top_frac" ## [191] "order_by" "dplyr_col_modify" ## [193] "rows_upsert" "group_indices_" ## [195] "funs" "etl" ## [197] "filter_if" "ungroup" ## [199] "arrange_at" "rows_patch" ## [201] "src_tbls" "make_tbl" ## [203] "db_commit" "find_schema" ## [205] "validate_grouped_df" "compare_tbls2" ## [207] "c_across" "add_rownames" ## [209] "slice_tail" "cur_group_rows" ## [211] "auto_copy" "group_by_" ## [213] "eval_tbls2" "arrange_" ## [215] "transmute_" "nth" ## [217] "group_trim" "lead" ## [219] "group_size" "as_tibble" ## [221] "collect" "inner_join" ## [223] "db_list_tables" "progress_estimated" ## [225] "etl_transform" "db_drop_table" ## [227] "smart_download" "group_by_if" ## [229] "add_tally" "if_else" ## [231] "cumany" "desc" ## [233] "cummean" "mutate" ## [235] "setdiff" "slice_min" ## [237] "with_order" "percent_rank" ## [239] "slice" "is.grouped_df" ## [241] "distinct_at" "group_by_at" ## [243] "quos" "slice_sample" ## [245] "distinct_prepare" "mutate_if" ## [247] "group_by_prepare" "rows_append" ## [249] "current_vars" "dense_rank" ## [251] "add_count_" "distinct_" ## [253] "summarize_at" "nest_by" ## [255] "wrap_dbplyr_obj" "mutate_at" ## [257] "sql_escape_string" "last_col" ## [259] "distinct_if" "lag" ## [261] "vars" "check_dbplyr" ## [263] "select_vars" "common_by" ## [265] "one_of" "with_groups" ## [267] "location" "%>%" ## [269] "rows_insert" "right_join" ## [271] "combine" "coalesce" ## [273] "cur_data" "starts_with" ## [275] "across" "group_by" ## [277] "lst" "group_vars" ## [279] "tally" "copy_to" ## [281] "db_write_table" "quo_name" ## [283] "left_join" "dbWipe" ## [285] "count_" "sample_frac" ## [287] "summarize_" "top_n" ## [289] "group_modify" "download.file" ## [291] "group_rows" "transmute_at" ## [293] ".data" "between" ## [295] "transmute_all" "recode" ## [297] "summarise_at" "n_distinct" ## [299] "validate_rowwise_df" "sample_n" ## [301] "rename" "st_intersection" ## [303] "st_read" "add_row" ## [305] "group_by_drop_default" "src_mysql_cnf" ## [307] "sql_select" "n_groups" ## [309] "rename_vars_" "enquos" ## [311] "filter_all" "filter_" ## [313] "is.src" "distinct_all" ## [315] "syms" "mutate_each_" ## [317] "new_rowwise_df" ``` --- ## package:macleish - objects that `macleish` **users** can see - exported objects ```r macleish_exports <- pkg_env("macleish") %>% env_names() macleish_exports ``` ``` ## [1] "macleish_layers" "mass_gis" ## [3] ".Depends" "maple_sap" ## [5] "whately_2015" "phenocam_image_url_midday" ## [7] "phenocam_image_url" "phenocam_info" ## [9] "orchard_2015" "phenocam_read_monthly_midday_urls" ## [11] "phenocam_read_day_urls" "macleish_intersect" ## [13] "tree_diameter1" "tree_diameter2" ## [15] "etl_transform_help" ```