{"id":15946296,"url":"https://github.com/nelson-gon/manymodelr","last_synced_at":"2025-10-19T06:30:40.778Z","repository":{"id":46071895,"uuid":"169533394","full_name":"Nelson-Gon/manymodelr","owner":"Nelson-Gon","description":"Build and Tune Several Models","archived":false,"fork":false,"pushed_at":"2021-12-27T15:50:34.000Z","size":6065,"stargazers_count":2,"open_issues_count":5,"forks_count":3,"subscribers_count":2,"default_branch":"master","last_synced_at":"2025-01-29T08:11:23.019Z","etag":null,"topics":["analysis-of-variance","anova","correlation","correlation-coefficient","cran","generalized-linear-models","gradient-boosting-decision-trees","knn-classification","linear-models","linear-regression","machine-learning","missing-values","models","package","r","r-package","r-programming","r-stats","random-forest-algorithm","regression-models"],"latest_commit_sha":null,"homepage":"https://nelson-gon.github.io/manymodelr/","language":"R","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"gpl-2.0","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/Nelson-Gon.png","metadata":{"files":{"readme":"README.Rmd","changelog":null,"contributing":".github/CONTRIBUTING.md","funding":null,"license":"LICENSE","code_of_conduct":".github/CODE_OF_CONDUCT.md","threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null}},"created_at":"2019-02-07T07:19:01.000Z","updated_at":"2021-12-27T15:50:37.000Z","dependencies_parsed_at":"2022-09-08T11:30:56.003Z","dependency_job_id":null,"html_url":"https://github.com/Nelson-Gon/manymodelr","commit_stats":null,"previous_names":[],"tags_count":10,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Nelson-Gon%2Fmanymodelr","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Nelson-Gon%2Fmanymodelr/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Nelson-Gon%2Fmanymodelr/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Nelson-Gon%2Fmanymodelr/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/Nelson-Gon","download_url":"https://codeload.github.com/Nelson-Gon/manymodelr/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":237073137,"owners_count":19251036,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["analysis-of-variance","anova","correlation","correlation-coefficient","cran","generalized-linear-models","gradient-boosting-decision-trees","knn-classification","linear-models","linear-regression","machine-learning","missing-values","models","package","r","r-package","r-programming","r-stats","random-forest-algorithm","regression-models"],"created_at":"2024-10-07T09:21:02.902Z","updated_at":"2025-10-19T06:30:40.772Z","avatar_url":"https://github.com/Nelson-Gon.png","language":"R","funding_links":[],"categories":[],"sub_categories":[],"readme":"---\ndate: \"`r Sys.Date()`\"\noutput: github_document\ntitle: \"manymodelr: Build and Tune Several Models\"\nvignette: \u003e\n  %\\VignetteIndexEntry{ \"A Gentle Introduction to manymodelr\"}\n  %\\VignetteEngine{rmarkdown}\n  %\\VignetteEncoding{UTF-8}\n---\n\n```{r setup, include = FALSE}\nopts_chunk$set(\n  collapse = TRUE,\n  comment = \"#\u003e\"\n)\n```\n\n\n\n[![CRAN_Status_Badge](https://www.r-pkg.org/badges/version/manymodelr)](https://CRAN.R-project.org/package=manymodelr)\n[![Codecov test coverage](https://codecov.io/gh/Nelson-Gon/manymodelr/branch/develop/graph/badge.svg)](https://app.codecov.io/gh/Nelson-Gon/manymodelr?branch=develop)\n[![DOI](https://zenodo.org/badge/DOI/10.5281/zenodo.3891106.svg)](https://zenodo.org/record/5211272)\n[![R CMDCheck](https://github.com/Nelson-Gon/manymodelr/workflows/R-CMD-check-devel/badge.svg)](https://github.com/Nelson-Gon/manymodelr)\n![test-coverage](https://github.com/Nelson-Gon/manymodelr/workflows/test-coverage/badge.svg)\n[![license](https://img.shields.io/badge/license-GPL--2-blue.svg)](https://www.gnu.org/licenses/gpl-3.0.en.html)\n[![CRAN\\_Release\\_Badge](https://www.r-pkg.org/badges/version-ago/manymodelr)](https://CRAN.R-project.org/package=manymodelr)\n[![Downloads](https://cranlogs.r-pkg.org/badges/manymodelr)](https://CRAN.R-project.org/package=manymodelr)\n[![TotalDownloads](https://cranlogs.r-pkg.org/badges/grand-total/manymodelr?color=yellow)](https://CRAN.R-project.org/package=manymodelr) \n[![lifecycle](https://img.shields.io/badge/lifecycle-stable-brightgreen.svg)](https://lifecycle.r-lib.org/articles/stages.html) \n[![Maintenance](https://img.shields.io/badge/Maintained%3F-yes-green.svg)](https://GitHub.com/Nelson-Gon/manymodelr/graphs/commit-activity) \n[![Project Status](https://www.repostatus.org/badges/latest/active.svg)](https://www.repostatus.org/) \n[![GitHub last commit](https://img.shields.io/github/last-commit/Nelson-Gon/manymodelr.svg)](https://github.com/Nelson-Gon/manymodelr/commits/master)\n[![GitHub issues](https://img.shields.io/github/issues/Nelson-Gon/manymodelr.svg)](https://GitHub.com/Nelson-Gon/manymodelr/issues/)\n[![GitHub issues-closed](https://img.shields.io/github/issues-closed/Nelson-Gon/manymodelr.svg)](https://GitHub.com/Nelson-Gon/manymodelr/issues?q=is%3Aissue+is%3Aclosed)\n[![PRs Welcome](https://img.shields.io/badge/PRs-welcome-brightgreen.svg?style=flat-square)](https://makeapullrequest.com)\n\nIn this vignette, we take a look at how we can simplify many machine learning tasks using `manymodelr`. \n\n\n## Installation \n\n```{r, eval=FALSE}\n\ninstall.packages(\"manymodelr\")\n\n```\n\nOnce the package has been successfully installed, we can then proceed by loading the package and exploring some of the key functions.\n\n\n\n**Loading the package**\n\n```{r}\n\nlibrary(manymodelr)\n\n# data for examples\ndata(\"yields\", package=\"manymodelr\")\n```\n\n\n## Modeling \n\nFirst, a word of caution. The examples shown in this section are meant to simply show what the functions do and not what the best model is. For a specific use case, please perform the necessary model checks, post-hoc analyses, and/or choose predictor variables and model types as appropriate based on domain knowledge.\n\nWith this in mind, let us look at how we can perform modeling tasks using `manymodelr`. \n\n\n- **`multi_model_1`**\n\nThis is one of the core functions of the package. `multi_model_1` aims to allow\nmodel fitting, prediction, and reporting with a single function. The `multi` \npart of the function's name reflects the fact that we can fit several model \ntypes with one function. An example follows next. \n\nFor purposes of this report, we create a simple dataset to use.\n\n\n\n\n```{r}\nset.seed(520)\ntrain_set\u003c-createDataPartition(yields$normal,p=0.6,list=FALSE)\nvalid_set\u003c-yields[-train_set,]\ntrain_set\u003c-yields[train_set,]\nctrl\u003c-trainControl(method=\"cv\",number=5)\nm\u003c-multi_model_1(train_set,\"normal\",\".\",c(\"knn\",\"rpart\"), \n                 \"Accuracy\",ctrl,new_data =valid_set)\n\n```\n\nThe above returns a list containing metrics, predictions, and a model summary.  These can be extracted as shown below. \n\n```{r}\n\nm$metric\n\n```\n\n```{r}\n\nhead(m$predictions)\n\n```\n\n- **multi_model_2**\n\nThis is similar to `multi_model_1` with one difference: it does not use metrics such as RMSE, accuracy and the like. This function is useful if one would like to fit and predict \"simpler models\" like generalized linear models or linear models. Let's take a look:\n\n\n\n\n```{r}\n# fit a linear model and get predictions\nlin_model \u003c- multi_model_2(mtcars[1:16,],mtcars[17:32,],\"mpg\",\"wt\",\"lm\")\n\nlin_model[c(\"predicted\", \"mpg\")]\n\n```\n\nFrom the above, we see that `wt` alone may not be a great predictor for `mpg`. We\ncan fit a multi-linear model with other predictors. Let's say `disp` and `drat` are important too, then we add those to the model.  \n\n```{r}\n\nmulti_lin \u003c- multi_model_2(mtcars[1:16, ], mtcars[17:32,],\"mpg\", \"wt + disp + drat\",\"lm\")\n\nmulti_lin[,c(\"predicted\", \"mpg\")]\n\n```\n\n \n\n- **`fit_model`**\n\nThis function allows us to fit any kind of model without necessarily returning predictions. \n \n```{r}\nlm_model \u003c- fit_model(mtcars,\"mpg\",\"wt\",\"lm\")\nlm_model\n\n```\n\n- `fit_models`\n\nThis is similar to `fit_model` with the ability to fit many models with many predictors at once. A simple linear model for instance:\n\n```{r}\n\nmodels\u003c-fit_models(df=yields,yname=c(\"height\", \"weight\"),xname=\"yield\",\n                   modeltype=\"glm\") \n\n```\n\nOne can then use these models as one may wish. To add residuals from these models for example:\n\n\n```{r}\n\n\nres_residuals \u003c- lapply(models[[1]], add_model_residuals,yields)\nres_predictions \u003c- lapply(models[[1]], add_model_predictions, yields, yields)\n# Get height predictions for the model height ~ yield \nhead(res_predictions[[1]])\n\n```\n\n\nIf one would like to drop non-numeric columns from the analysis, one can set `drop_non_numeric` to `TRUE` as follows. The same can be done for `fit_model` above:\n\n```{r}\n(models\u003c-fit_models(df=yields,yname=c(\"height\",\"weight\"),\n           xname=\".\",modeltype=c(\"lm\",\"glm\"), drop_non_numeric = TRUE))\n\n```\n\n## Generating a (simple) model report\n\nOne can generate a very simple model report using `report_model` as follows:\n\n```{r}\nreport_model(models[[2]][[1]])\n```\n\n\n## Extraction of Model Information\n\n\nTo extract information about a given model, we can use `extract_model_info` as follows.\n\n```{r}\n\nextract_model_info(lm_model, \"r2\")\n\n```\n\nTo extract the adjusted R squared:\n\n```{r}\n\nextract_model_info(lm_model, \"adj_r2\")\n\n```\n\nFor the p value:\n\n```{r}\n\nextract_model_info(lm_model, \"p_value\")\n\n```\n\nTo extract multiple attributes:\n\n```{r}\n\nextract_model_info(lm_model,c(\"p_value\",\"response\",\"call\",\"predictors\"))\n\n```\n\nThis is not restricted to linear models but will work for most model types. See `help(extract_model_info)` to see currently supported model types.\n\n\n\n\n## Correlations \n\n\n- `get_var_corr`\n\nAs can probably(hopefully) be guessed from the name, this provides a convenient way to get variable correlations. It enables one to get correlation between one variable and all other variables in the data set.\n\n**Previously, one would set `get_all` to `TRUE` if they wanted to get correlations between all variables. This argument has been dropped in favor of simply supplying an optional `other_vars` vector if one does not want to get all correlations.** \n\nSample usage:\n\n```{r}\n\n# getall correlations\n\n# default pearson\n\nhead( corrs \u003c- get_var_corr(mtcars,comparison_var=\"mpg\") )\n\n\n```\n\n**Previously, one would also set `drop_columns` to `TRUE` if they wanted to drop factor columns.** Now, a user simply provides a character vector specifying which column types(classes) should be dropped. It defaults to `c(\"character\",\"factor\")`.\n\n```{r}\n\n# purely demonstrative\nget_var_corr(yields,\"height\",other_vars=\"weight\",\n             drop_columns=c(\"factor\",\"character\"),method=\"spearman\",\n             exact=FALSE)\n\n\n```\n\n\nSimilarly, `get_var_corr_` (note the underscore at the end) provides  a convenient way to get combination-wise correlations.\n\n```{r}\n\nhead(get_var_corr_(yields),6)\n\n```\n\nTo use only a subset of the data, we can use provide a list of columns to `subset_cols`. By default, the first value(vector) in the list is mapped to `comparison_var` and the other to `other_Var`. The list is therefore of length 2.\n\n```{r}\n\nhead(get_var_corr_(mtcars,subset_cols=list(c(\"mpg\",\"vs\"),c(\"disp\",\"wt\")),\n                   method=\"spearman\",exact=FALSE))\n\n```\n\n\n- `plot_corr`\n\nObtaining correlations would mostly likely benefit from some form of visualization. `plot_corr` aims to achieve just that. There are currently two plot styles, `squares` and `circles`. `circles` has a `shape` argument that can allow for more flexibility. It should be noted that the correlation matrix supplied to this function is an object produced by `get_var_corr_`.\n\n\n\nTo modify the plot a bit, we can choose to switch the x and y values as shown below.\n\n```{r}\n\n\nplot_corr(mtcars,show_which = \"corr\",\n          round_which = \"correlation\",decimals = 2,x=\"other_var\",  y=\"comparison_var\",plot_style = \"squares\"\n          ,width = 1.1,custom_cols = c(\"green\",\"blue\",\"red\"),colour_by = \"correlation\")\n\n```\n\n\nTo show significance of the results instead of the correlations themselves, we can set `show_which` to \"signif\"  as shown below. By default, significance is set to 0.05. You can override this by supplying a different `signif_cutoff`.\n\n```{r}\n# color by p value\n# change custom colors by supplying custom_cols\n# significance is default \nset.seed(233)\nplot_corr(mtcars, x=\"other_var\", y=\"comparison_var\",plot_style = \"circles\",show_which = \"signif\", colour_by = \"p.value\", sample(colours(),3))\n\n```\n\n\n\nTo explore more options, please take a look at the documentation.\n\n## Extra Functions \n\n\n\n- **`agg_by_group`**\n\nAs can be guessed from the name, this function provides an easy way to manipulate grouped data. We can for instance find the number of observations in the yields data set. The formula takes the form `x~y` where `y` is the grouping variable(in this case `normal`). One can supply a formula as shown next. \n\n```{r}\n\nhead(agg_by_group(yields,.~normal,length))\n\n```\n\n```{r}\n\nhead(agg_by_group(mtcars,cyl~hp+vs,sum))\n\n```\n\n\n- `rowdiff`\n\n This is useful when trying to find differences between rows. The `direction` argument specifies how the subtractions are made while the `exclude` argument is used to specify classes that should be removed before calculations are made.  Using `direction=\"reverse\"` performs a subtraction akin to `x-(x-1)` where `x` is the row number. \n\n```{r}\n\nhead(rowdiff(yields,exclude = \"factor\",direction = \"reverse\"))\n\n```\n\n\n- `na_replace`\n\nThis allows the user to conveniently replace missing values. Current options are `ffill` which replaces with the next non-missing value, `samples` that samples the data and does replacement, `value` that allows one to fill `NA`s with a specific value. Other common mathematical methods like `min`, `max`,`get_mode`, `sd`, etc are no longer supported. They are now available with more flexibility in standalone [mde](https://github.com/Nelson-Gon/mde)\n\n```{r}\n\nhead(na_replace(airquality, how=\"value\", value=\"Missing\"),8)\n\n```\n\n- `na_replace_grouped`\n\nThis provides a convenient way to replace values by group.\n```{r}\ntest_df \u003c- data.frame(A=c(NA,1,2,3), B=c(1,5,6,NA),groups=c(\"A\",\"A\",\"B\",\"B\"))\n# Replace NAs by group\n# replace with the next non NA by group.\nna_replace_grouped(df=test_df,group_by_cols = \"groups\",how=\"ffill\")\n\n```\n\nThe use of `mean`,`sd`,etc is no longer supported. Use [mde](https://github.com/Nelson-Gon/mde) instead which is focused on missingness. \n\n---\n\n**Exploring Further**\n\nThe vignette has been short and therefore is non exhaustive. The best way to explore this and any package or language is to practise. For more examples, please use `?function_name` and see a few implementations of the given function.\n\n**Reporting Issues**\n\nIf you would like to contribute, report issues or improve any of these functions, please raise a pull request at ([manymodelr](https://github.com/Nelson-Gon/manymodelr))\n\n\u003e \"Programs must be written for people to read, and only incidentally for machines to execute.\" - Harold Abelson ([Reference](https://www.goodreads.com/quotes/tag/programming))\n\n**Thank You**\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fnelson-gon%2Fmanymodelr","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fnelson-gon%2Fmanymodelr","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fnelson-gon%2Fmanymodelr/lists"}