{"id":25515373,"url":"https://github.com/izalu99/past-project-reports","last_synced_at":"2026-01-27T15:03:19.060Z","repository":{"id":164969682,"uuid":"607021717","full_name":"izalu99/past-project-reports","owner":"izalu99","description":"Statistical Projects with R and knitr","archived":false,"fork":false,"pushed_at":"2025-02-14T05:13:29.000Z","size":42,"stargazers_count":1,"open_issues_count":0,"forks_count":0,"subscribers_count":0,"default_branch":"main","last_synced_at":"2025-05-20T21:37:22.066Z","etag":null,"topics":["predictive-modeling","statistics"],"latest_commit_sha":null,"homepage":"","language":null,"has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/izalu99.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2023-02-27T06:25:47.000Z","updated_at":"2025-02-14T05:15:18.000Z","dependencies_parsed_at":"2023-07-15T02:15:33.901Z","dependency_job_id":null,"html_url":"https://github.com/izalu99/past-project-reports","commit_stats":null,"previous_names":["izalu99/past-project-reports"],"tags_count":0,"template":false,"template_full_name":null,"purl":"pkg:github/izalu99/past-project-reports","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/izalu99%2Fpast-project-reports","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/izalu99%2Fpast-project-reports/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/izalu99%2Fpast-project-reports/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/izalu99%2Fpast-project-reports/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/izalu99","download_url":"https://codeload.github.com/izalu99/past-project-reports/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/izalu99%2Fpast-project-reports/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":28815385,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2026-01-27T12:25:15.069Z","status":"ssl_error","status_checked_at":"2026-01-27T12:25:05.297Z","response_time":168,"last_error":"SSL_read: unexpected eof while reading","robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":false,"can_crawl_api":true,"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":["predictive-modeling","statistics"],"created_at":"2025-02-19T13:29:46.012Z","updated_at":"2026-01-27T15:03:19.045Z","avatar_url":"https://github.com/izalu99.png","language":null,"funding_links":[],"categories":[],"sub_categories":[],"readme":"# Project 1\n---\ntitle: 'Project 1 : Predicting the weight of bananas'\nauthor: \"Iza\"\ndate: \"2/6/2022\"\noutput:\n  pdf_document: default\n  word_document: default\n  html_document:\n    df_print: paged\n---\n\n```{r, setup, include=FALSE}\nknitr::opts_chunk$set(echo = TRUE)\nknitr::opts_chunk$set(fig.width = 8)\nknitr::opts_chunk$set(fig.show = T)\nknitr::opts_chunk$set(fig.cap = T)\n```\n\n```{r wrap-hook, include=FALSE}\nlibrary(knitr)\nhook_output = knit_hooks$get('output')\nknit_hooks$set(output = function(x, options) {\n  # this hook is used only when the linewidth option is not NULL\n  if (!is.null(n \u003c- options$linewidth)) {\n    x = knitr:::split_lines(x)\n    # any lines wider than n should be wrapped\n    if (any(nchar(x) \u003e n)) x = strwrap(x, width = n)\n    x = paste(x, collapse = '\\n')\n  }\n  hook_output(x, options)\n})\n```\n\n```{r include=FALSE}\nlibrary(knitr)\nlibrary(ggplot2)\nlibrary(GGally)  # an extension to ggplot2\nlibrary(Metrics)\n```\n\n```{r, echo=FALSE}\n# import the banana data\nbdata = readxl::read_xlsx(\"Copy of Banana Data.xlsx\")\n\ncolnames(bdata) = c(\"weight\",\"length\",\"radius\")\n\n```\n\n```{r, echo=FALSE}\n# split data into train and test subsets\n# test data are rows:1,8,12,17,18,23,24,28,44,45,47,53,55,69,76,77\ntestrows = c(1,8,12,17,18,23,24,28,44,45,47,53,55,69,76,77)\nbanana_train = bdata[-testrows,] \nbanana_test = bdata[testrows,]\n\n```\n\n\n## Summary\nThis report is about predicting the weight of bananas (given its radius and length), by using linear regression. A sample data of size, n= 78 is collected,then split into training dataset and test data set for cross validation of the model. The Mean Absolute Value and Mean Absolute Percent Error are also used for further evaluation of the models. A weighted linear model is generated to be the final linear model. \n\n## Introduction\n### Background\nA known formula for computing the weight of an object is \n$Weight = Density \\times Volume.$ If a cylinder has the volume defined as $Volume = \\pi \\times radius^2 \\times length$ then, we would have an approximate formula of weight as \n$Weight = Density \\times \\pi \\times radius^2 \\times length.$ \\\n\n\n\n### Purpose\nIf we assume that a banana is technically a cylinder then we can approximate its weight given its length and radius. Since the log function $log()$ has the property of $log(XY^m) = log(X) + mlog(X)$ we can use it to transform the weight equation above into a linear form. By doing so we can use a linear regression model to predict the weight of a banana. Applying the log function the new equation we use for linear regression is\n$log(Weight) = log(Density) + log(\\pi) + 2log(radius) + log(length).$ \\\n\nThen further modified into \n$log(Weight) = \\beta_0 + \\beta_1 log(radius) + \\beta_2 log(length).$\\\n\n\\\nwhere we have the constants in $\\beta_0.$ \n\\\n\nThe linear regression will then estimate the values of $\\beta_0, \\beta_1, \\beta_2$ \n\n## Methods\n\n### Data collection\nEach student is tasked to measure the radius, length and weight of six bananas which is compiled together into a dataset with 78 rows and 3 columns. \n\n\n### Exploratory data analysis\nTo get a glimpse of the data, a correlation plot is generated. From the pairwise plot below, its found that the variables have weak to moderate linear relationship with each other.\n\n```{r, echo=FALSE, fig.cap= \"Pairwise plot with the correlation of each variable in the data\"}\nggpairs(data = banana_train, \n        axisLabels = \"show\")\n```\n\n### Model Building\nThere are three linear models to choose from: \\\n\n- $log(Weight) = \\beta_0 + \\beta_1 log(radius) + \\beta_2 log(length) + \\varepsilon$\\\n- $log(Weight) = \\beta_0 + \\beta_1 log(length) + \\varepsilon$\\\n- $log(Weight) = \\beta_0 + \\beta_1 log(radius) + \\varepsilon$ \\\n\\\nFor each model, we use the *lm()* to generate the estimates of the coefficients, $\\beta_0, \\beta_1$, and the residuals,$\\varepsilon$. But, before applying *lm()*, the original  dataset is split into a training and test set where, we use the train set to build the models. Once the models are built,the models are assessed by comparing their Mean Absolute Error(MAE) and Mean Absolute Percent Error(MAPE). The model that yields the lowest MAE and MAPE is chosen to be the model for prediction. The assumptions for linear regression have to be checked on each model, if any assumption is validated, the model is modified. \\\n\n\n## Results\n\nOnce the models are generated, the estimated coefficients are on the table below. \\\n```{r =FALSE}\n\nlinfit_full = lm(log(weight) ~ log(length) + log(radius),data=banana_train)   #all variables\nlinfit_l = lm(log(weight)~log(length), data=banana_train)                    #just length as x\nlinfit_r = lm(log(weight)~log(radius), data=banana_train)                    #just radius as x\nlinfit_none = lm(weight~1, data=banana_train)                   #empty; used for forward step, model selection\n\nsummary(linfit_full)\nsummary(linfit_l)\nsummary(linfit_r)\nsummary(linfit_none)\n```\n```{r echo=F}\nlinfit_b0 = c(linfit_full$coefficients[1], linfit_l$coefficients[1], linfit_r$coefficients[1])\nlinfit_b1 = c(linfit_full$coefficients[2], linfit_l$coefficients[2], linfit_r$coefficients[2])\nlinfit_b2 = c(linfit_full$coefficients[3], NA, NA)\nlinfit_coefs = \n  cbind.data.frame(\n  c(\"linfit_full\",\"linfit_l\",\"linfit_r\"),\n  linfit_b0,linfit_b1,linfit_b2)\nnames(linfit_coefs)[1] =\"model\"\nkable(linfit_coefs, format=\"pipe\")\n```\n\\\n\\\n\\\n\\\n\\\nThus, the linear models are: \\\n\n- **linfit_full**: $log(Weight) = 0.918 + (0.121) log(radius) + (1.182) log(length)$ \\\n- **linfit_l**: $log(Weight) = 3.492 + (0.281) log(length)$ \\\n- **linfit_r**: $log(Weight) = 1.294 + (1.278) log(radius)$ \\\n\nFrom just the adjusted R-squared values of each model, **linfit_r** had the highest value of $0.2092$. This means that the predictor in **linfit_r*** (radius), is responsible of the response variable's (weight) variablity of about 20.92%. When the Step wise method is used for Akaike Information Criterion (AIC) and Bayesian Information Criterion(BIC), the model produced is the as **linfit_r**. So by comparing the adjusted R-squared values and performing variable selection by AIC and BIC, **linfit_r** seems to be the best model among the three. \\\n\n```{r include=FALSE}\n# backwards, using both length and radius variables\nstep(linfit_full, direction=\"backward\", trace=F)\n\n# forward...\nstep(linfit_none, direction=\"forward\", scope = list(lower= linfit_none, upper= linfit_full), trace=F)\n\n# Result is the model with radius as the predictor\n```\n\n### Results of cross validation\n\n```{r include=FALSE}\n# using the model with all the variables (l and  r)\npred.full = predict(object = linfit_full, newdata = banana_test)\n\n# with just length (l)\npred.l = predict(object = linfit_l, newdata = banana_test)\n\n# with just radius (r)\npred.r = predict(object = linfit_r, newdata = banana_test)\n```\n\n```{r include=FALSE}\n# MAE - Mean absolute error\n# MPAE - Mean Percent absolute error\n# function to compute MAE\ncomputeMae = function(measured,predicted,n){\n  summed_term = 0\n  for (i in 1:n){\n    abs_term = abs(measured[i]-predicted[i])\n    summed_term = summed_term + abs_term\n  }\n  \n  MAE = summed_term/n\n  \n  return(MAE)\n}\n```\n\n```{r include=FALSE}\n#----MAE\nMAE_train_full = computeMae(log(banana_train$weight), linfit_full$fitted.values, n=nrow(banana_train))\nMAE_test_full = computeMae(log(banana_test$weight), log(pred.full), n= nrow(banana_test))\nmae_full = c(MAE_train_full, MAE_test_full)\n\nMAE_train_l = computeMae(log(banana_train$weight), linfit_l$fitted.values, n= nrow(banana_train))\nMAE_test_l = computeMae(log(banana_test$weight), log(pred.l), n= nrow(banana_test))\nmae_l = c(MAE_train_l, MAE_test_l)\n\nMAE_train_r = computeMae(log(banana_train$weight), linfit_r$fitted.values, n= nrow(banana_train))\nMAE_test_r = computeMae(log(banana_test$weight), log(pred.r), n= nrow(banana_test))\nmae_r = c(MAE_train_r, MAE_test_r)\n\nmae_df = cbind.data.frame(mae_full, mae_l, mae_r)\n\nrownames(mae_df) = c(\"weight(train)\",\"weight(test)\")\ncolnames(mae_df) = c(\"predicted weight(full)\", \"predicted weight(length)\", \"predicted weight(radius)\")\n\nmae_table = kable(mae_df,format= \"pipe\", row.names = T)\n\n\n#----MAPE\n# use mape() in Metrics package\nMAPE_train_full = mape(log(banana_train$weight), linfit_full$fitted.values)\nMAPE_test_full = mape(log(banana_test$weight), log(pred.full))\nmape_full = c(MAPE_train_full,MAPE_test_full)\n\nMAPE_train_l = mape(log(banana_train$weight), linfit_l$fitted.values)\nMAPE_test_l = mape(log(banana_test$weight), log(pred.l))\nmape_l = c(MAPE_train_l, MAPE_test_l)\n\nMAPE_train_r = mape(log(banana_train$weight), linfit_r$fitted.values)\nMAPE_test_r = mape(log(banana_test$weight), log(pred.r))\nmape_r = c(MAPE_train_r, MAPE_test_r)\n\n#put in df\nmape_df = cbind(mape_full, mape_l, mape_r)\nrownames(mape_df) = c(\"obs.weight(train)\",\" obs.weight(test)\")\ncolnames(mape_df) = c(\"pred.weight(full)\", \"pred.weight(length)\", \"pred.weight(radius)\")\n\n#then table\nmape_table = kable(mape_df, row.names = T)\n```\n\nIn order to perform a cross validation, the models are used to predict the weight of bananas using the test dataset. The resulting MAE and MAPE values are: \\\n\n```{r echo=TRUE, fig.cap=\"MAE table\", paged.print=FALSE}\nmae_table\n# The lesser the percent value of mae/mape, the more accurate the model\n```\n*MAE values; The column name correspond to the which model generated the predicted values and the row name is where the observed values are from.*\n\\\n```{r echo=TRUE, fig.cap=\"MAE table\", paged.print=TRUE}\nmape_table\n```\n*MAPE values; The column name correspond to the which model generated the predicted values and the row name is where the observed values are from.* \\\n\nFrom the MAE and MAPE tables, we can see that, the linear model  with radius as the sole predictor(**linfit_r**) and the model with length as the predictor(**linfit_l**),have the same values of MAE and MAPE when the test dataset is used to predict the weight. If we consider the MAE and MAPE values when predicted weight is generated by the train dataset we can see that **linfit_r** has a lower value for both measurements. Thus, MAE and MAPE confirms that **linfit_r** is the best among the three linear models.\n\n\n### Validity of the model\nIn order for the predicted values to be valid and to make other inferences from the the **linfit_r** model, the assumptions for linear regression is checked. \\\n\n```{r echo=FALSE, fig.cap= \"Diagnostic plots for the model:linfit.r\"}\n#radius\npar(mfrow=c(2,2))\nplot(linfit_r)\n```\n\n```{r include=FALSE}\n# Shapiro-Wilk Normality Test\n#H_0: The residuals are normally distributed\n#H_1: The residuals are not normally distributed\nshapiro.test(linfit_r$residuals)\n```\n\n\n- ***Linearity***: The *Residuals vs. Fitted* graph has an approximately horizontal line which means that there is no fitted pattern. Thus, we can assume that the radius has a linear relationship with the weight. \\\n \n- ***Residual's normality test***: After running a Shapiro-Wilk Normality Test with a significance level of 0.05, we fail to reject the null hypothesis since $p-value = 0.6425 \u003e (2*0.05)$. This means that we have 95% confidence of the residuals being normally distributed. \\\n \n- **Homoscedasticity(equal variances)**: From the plot of Scale-Location we can see that the line is not horizontal which implies that variance of the residuals increases with the fitted values. This imply that **linfit_r** produces non-constant variance of the response variable (banana weights). Adding weights to the model done in the next section overcomes this violation. \\\n \n\\\n```{r, echo=FALSE, fig.cap= \"Boxplots of the variables\"}\n#boxplot\npar(mfrow=c(1,3))\nboxplot(banana_train$weight, ylab = \"Weight(g)\", main = \"Boxplot of Banana weights\", col=\"lightyellow\")\nboxplot(banana_train$length, ylab = \"length(mm)\", main = \"Boxplot of Banana length\", col=\"lightgreen\")\nboxplot(banana_train$radius, ylab = \"radius(mm)\", main = \"Boxplot of Banana radius\", col=\"lightpink\")\n```\n\n- **Outliers and influential points**: The *Residuals vs. Leverage* Graph, show that there is no point that crosses Cook's distance. Therefore, there are no influential points that we could omit. So even though there seemed to be some radius outliers shown on the boxplot, removing them would not have a significant effect on the model.\n\n### Modifying the model\n\n\nBy adding the weight $w_i = \\frac{1}{(st.dev(Y_i))^2}$ to the **linfit_r** model we get a new model (**fitr_wi**): \\\n$$log(Weight)_w = \\hat{\\beta_{0}} + \\hat{\\beta_{1}} log(radius)_w + \\hat{\\varepsilon},$$\nwhere $_w$ represents the weights added on the observations[1]. \\\nApplying the weights on the linear model resulted in a small improvement of the Adjusted R-squared from $0.2092$ to $0.2928$. The figure below confirms small improvement as the scale location graph became a bit more horizontal.  \n\\\n```{r}\n# add a weight to stabilize the variance\n# weight  = 1/(residuals)^2; we estimate the residuals via slr for it\nresfit = lm(abs(linfit_r$residuals)~ linfit_r$fitted.values)\n\nwi = 1/resfit$fitted.values^2\nfitr_wi = lm(log(weight)~log(radius), data=banana_train, weights = wi)\n\nsummary(fitr_wi)\n\n```\n\\\n```{r}\npar(mfrow=c(2,2))\nplot(fitr_wi)\n\n```\n\\\nWhen **fitr_wi** is used to predict the banana weights with the test dataset, the resulting MAE and MAPE are: \\\n\\\n```{r echo=FALSE, table.cap=\"MAE and MAPE with the fitr_wi model\"}\n# predict weight using fitr_w8\npred.rwi = predict(object = fitr_wi, newdata = banana_test)\n\n#MAE\nmae_rwi = computeMae(log(banana_test$weight), pred.rwi, n= nrow(banana_test))\n\n#MAPE\nmape_rwi = mape(log(banana_test$weight), pred.rwi)\n\n# to make a line plot of your regression model:\n#ggplot(fitr_w8, aes(names(fitr_w8)[2], names(fitr_w8)[1])) + geom_abline()\n\nmaepe_table = data.frame(mae_rwi,mape_rwi)\nnames(maepe_table)[1] = \"MAE\"\nnames(maepe_table)[2] = \"MAPE\"\nkable(maepe_table, format=\"pipe\")\n```\n\\\n*The MAE and MAPE values above are computed from the test dataset.* \\\n\n### Final model \n\nThe final model is **fitr_wi**:\n$$log(Weight)_w = \\hat{\\beta_0} + \\hat{\\beta_1} log(radius)_w + \\hat{\\varepsilon},$$\nwhere $\\hat{\\beta_0}= 1.395139, \\hat{\\beta_1}= 1.243427.$\\\n\n\nThe following graph is the models **linfit_r**(purple), and **fitr_wi**(blue) overlaying the plot of banana weights from the test test data set.\n\\\n```{r echo=FALSE, fig.cap=\"linfit_r(purple) and fitr_wi model(blue)\"}\nplot(x=banana_test$radius, y = banana_test$weight, type='p', col='red')\n\n#overlay line plot of linfit_r predictions\nlines(banana_test$radius, exp(pred.r), col='blue')\n\n#overlay line plot of fitr_wi predictions\nlines(banana_test$radius, exp(pred.rwi), col='purple')\n\n#add legend\nlegend(1, 25, legend=c('Line 1', 'Line 2', 'Line 3'),\n       col=c('red', 'blue', 'purple'), lty=1)\n```\n\\\n\nThe predicted banana weights are: \\\n\n```{r echo=FALSE}\nbweight_df = data.frame(banana_test$radius, banana_test$weight, exp(pred.r),exp(pred.rwi))\nprint(bweight_df)\n```\n\nWhile the 95% CI of the density is\n```{r}\n# confidence interval for the density\n# density is in the intercept (beta_0) term of linfit_full\nb0_full = linfit_r$coefficients[1]\n# st error of intercept in linfit_r: 49.059\nq.se = qnorm(1-(0.05/2))*49.059\nconfidence_i = b0_full + c(-1,1)*q.se\nq.se2 = 25.78\nconfidence_i + c(-1,1)*q.se2\n```\n## Conclusion\nEven though MAE and MAPE values are small the linear regression **fitr_wi** may not be the best model to predict the weight of bananas. That is because the Adjusted R-squared values are not high enough which means that the predictor variable (i.e., radius) does not predict the response (banana weight) very well. More predictor variables could possibly improve the linear model. For instance, the ripeness of the banana (ripe/unripe). Adding size (e.g.,small/medium/large) might also allow for separate prediction models based on each size. Moreover, variance could be minimized during data collection by implementing the same techniques and tools in measuring the radius, length and weight of the banana. Non linear models may also yield better predictions.\n\n\n## Appendix\nThe following are the R codes used for this report.\n\\\n\n```{r, linewidth=60}\n#library(knitr)\n##library(ggplot2)\n#library(GGally)  # an extension to ggplot2\n#library(Metrics)\n```\n\n```{r, linewidth=60}\n# import the banana data\n#bdata = readxl::read_xlsx(\n#\"Banana Data.xlsx\")\n\n#colnames(bdata) = c(\"weight\",\"length\",\"radius\")\n\n```\n\n```{r, linewidth=60}\n# split data into train and test subsets\n# test data are rows:\n#1,8,12,17,18,23,24,28,44,45,47,53,55,69,76,77\n#testrows = c(1,8,12,17,18,\n#23,24,28,44,45,47,53,55,69,76,77)\n#banana_train = bdata[-testrows,] \n#banana_test = bdata[testrows,]\n\n```\n\n```{r, linewidth=60}\n#ggpairs(data = banana_train, \n#        title = \n#\"Pairwise plot of the three variables in the data\", \n#        axisLabels = \"show\")\n# https://www.\n#rdocumentation.org/packages/GGally/versions/\n#1.5.0/topics/ggpairs \n# stars signify significance at 10%, 5% and 1% levels. https://r-coder.com/correlation-plot-r/ \n\n```\n\n```{r, fig.cap= \"Histogram of weight distribution of the bananas in the training set.\", linewidth=60}\n# histogram of the weight's distribution\n#hist(banana_train$weight, col = \"lightyellow\", \n#     border=\"black\", prob= T, \n#     xlab=\" banana weight (g)\", \n#main = \" Histogram of bananas' weight distribution\")\n\n#lines(density(banana_train$weight), lwd = 2.5, col = \"orange\")\n```\n\n\n```{r, linewidth=60}\n\n#linfit_full = lm(log(weight) ~ log(length) + log(radius),data=banana_train)   #all variables\n#linfit_l = lm(log(weight)~log(length), data=banana_train)                    #just length as x\n#linfit_r = lm(log(weight)~log(radius), data=banana_train)                    #just radius as x\n#linfit_none = lm(weight~1, data=banana_train)                   #empty; used for forward step, model selection\n\n#summary(linfit_full)\n#summary(linfit_l)\n#summary(linfit_r)\n#summary(linfit_none)\n```\n```{r}\n#linfit_b0 = c(linfit_full$coefficients[1], linfit_l$coefficients[1], linfit_r$coefficients[1])\n#linfit_b1 = c(linfit_full$coefficients[2], linfit_l$coefficients[2], linfit_r$coefficients[2])\n#linfit_b2 = c(linfit_full$coefficients[3], NA, NA)\n#linfit_coefs = cbind.data.frame(c(\"linfit_full\",\"linfit_l\",\n#\"linfit_r\"),linfit_b0,linfit_b1,linfit_b2)\n#names(linfit_coefs)[1] =\"model\"\n#kable(linfit_coefs, format=\"simple\")\n\n```\n\n\n*Not really need to do this, since there are only 2 possible predictors*).\n\\\n```{r echo=TRUE}\n# backwards, using both length and radius variables\n#step(linfit_full, direction=\"backward\", trace=F)\n\n# forward...\n#step(linfit_none, direction=\"forward\", scope = list(lower= linfit_none, upper= linfit_full), trace=F)\n\n# Result is the model with radius as the predictor\n```\n\n```{r}\n# using the model with all the variables (l and  r)\n#pred.full = predict(object = linfit_full, newdata = banana_test)\n\n# with just length (l)\n#pred.l = predict(object = linfit_r, newdata = banana_test)\n\n# with just radius (r)\n#pred.r = predict(object = linfit_r, newdata = banana_test)\n```\n\n\n\nComparing the models's accuracy\n\n```{r}\n# MAE - Mean absolute error\n# MPAE - Mean Percent absolute error\n# function to compute MAE\n#computeMae = function(measured,predicted,n){\n#  summed_term = 0\n# for (i in 1:n){\n#    abs_term = abs(measured[i]-predicted[i])\n#    summed_term = summed_term + abs_term\n#  }\n  \n#  MAE = summed_term/n\n  \n#  return(MAE)\n#}\n```\n\n```{r, linewdith=60}\n# now compare all the maes of train and test on each model\n#----MAE\n#MAE_train_full = computeMae(log(banana_train$weight), linfit_full$fitted.values, n=nrow(banana_train))\n#MAE_test_full = computeMae(log(banana_test$weight), \n#pred.full, n= nrow(banana_test))\n#mae_full = c(MAE_train_full, MAE_test_full)\n\n#MAE_train_l = computeMae(log(banana_train$weight), linfit_l$fitted.values, n= nrow(banana_train))\n#MAE_test_l = computeMae(log(banana_test$weight), \n#pred.l, n= nrow(banana_test))\n#mae_l = c(MAE_train_l, MAE_test_l)\n\n#MAE_train_r = computeMae(log(banana_train$weight), linfit_r$fitted.values, n= nrow(banana_train))\n#MAE_test_r = computeMae(log(banana_test$weight), pred.r, \n#n= nrow(banana_test))\n#mae_r = c(MAE_train_r, MAE_test_r)\n\n#mae_df = cbind.data.frame(mae_full, mae_l, mae_r)\n\n#rownames(mae_df) = c(\"weight(train)\",\"weight(test)\")\n#colnames(mae_df) = c(\"predicted weight(full)\", \"predicted weight(length)\", \"predicted weight(radius)\")\n\n#mae_table = kable(mae_df,format= \"pipe\", row.names = T)\n\n\n#----MAPE\n# use mape() in Metrics package\n#MAPE_train_full = mape(log(banana_train$weight), linfit_full$fitted.values)\n#MAPE_test_full = mape(log(banana_test$weight), pred.full)\n#mape_full = c(MAPE_train_full,MAPE_test_full)\n\n#MAPE_train_l = mape(log(banana_train$weight), linfit_l$fitted.values)\n#MAPE_test_l = mape(log(banana_test$weight), pred.l)\n#mape_l = c(MAPE_train_l, MAPE_test_l)\n\n#MAPE_train_r = mape(log(banana_train$weight), linfit_r$fitted.values)\n#MAPE_test_r = mape(log(banana_test$weight), pred.r)\n#mape_r = c(MAPE_train_r, MAPE_test_r)\n\n#put in df\n#mape_df = cbind(mape_full, mape_l, mape_r)\n#rownames(mape_df) = c(\"weight(train)\",\"weight(test)\")\n#colnames(mape_df) = c(\"predicted weight(full)\", \"predicted weight(length)\", \"predicted weight(radius)\")\n\n#then table\n#mape_table = kable(mape_df,format= \"pipe\", row.names = T)\n```\n\n\n```{r, echo=FALSE, fig.cap= \"Mean Absolute Error(Banana weight observations minus the three models's predicted weight\"}\n#mae_table\n# The lesser the percent value of mae/mape, the more accurate the model\n```\n\n```{r, echo=FALSE,fig.cap= \"Mean Absolute Percent Error (Banana weight observations minus the three models's predicted weight\"}\n#mape_table\n```\n\n```{r, echo=FALSE,fig.cap= \"Diagnostic plots for the model: linfit.full\"}\n#plot to check assumptions for linear regression\n#full\n#par(mfrow=c(2,2))\n#plot(linfit_full)\n```\n```{r, echo=FALSE, fig.cap= \"Diagnostic plots for the model:linfit.l\"}\n#length\n#par(mfrow=c(2,2))\n#plot(linfit_l)\n```\n\n```{r, echo=FALSE, fig.cap= \"Diagnostic plots for the model:linfit.r\"}\n#radius\n#par(mfrow=c(2,2))\n#plot(linfit_r)\n```\n\n```{r}\n# Shapiro-Wilk Normality Test\n#H_0: The residuals are normally distributed\n#H_1: The residuals are not normally distributed\n#shapiro.test(linfit_r$residuals)\n```\n\n```{r, echo=FALSE, fig.cap= \"Boxplots of the variables\"}\n#boxplot\n#par(mfrow=c(1,3))\n#boxplot(banana_train$weight, ylab = \"Weight(g)\", main = \"Boxplot of Banana weights\", col=\"lightyellow\")\n#boxplot(banana_train$length, ylab = \"length(mm)\", main = \"Boxplot of Banana length\", col=\"lightgreen\")\n#boxplot(banana_train$radius, ylab = \"radius(mm)\", main = \"Boxplot of Banana radius\", col=\"lightpink\")\n```\n\n```{r include=FALSE}\n# add a weight to stabilize the variance\n# weight  = 1/(residuals)^2; we estimate the residuals via slr for it\n#resfit = lm(abs(linfit_r$residuals)~ linfit_r$fitted.values)\n\n#wi = 1/resfit$fitted.values^2\n#fitr_wi = lm(log(weight)~log(radius), data=banana_train, weights = wi)\n#summary(fitr_wi)\n```\n```{r echo=FALSE}\n#par(mfrow=c(2,2))\n#plot(fitr_wi)\n```\n\n```{r echo=FALSE, table.cap=\"MAE and MAPE with the fitr_wi model\"}\n# predict weight using fitr_w8\n#pred.rwi = predict(object = fitr_wi, newdata = banana_test)\n\n#MAE\n#mae_rwi = computeMae(log(banana_test$weight), pred.rwi, n= nrow(banana_test))\n\n#MAPE\n#mape_rwi = mape(log(banana_test$weight), pred.rwi)\n\n# to make a line plot of your regression model:\n#ggplot(fitr_w8, aes(names(fitr_w8)[2], names(fitr_w8)[1])) + geom_abline()\n\n#maepe_table = data.frame(mae_rwi,mape_rwi)\n#names(maepe_table)[1] = \"MAE\"\n#names(maepe_table)[2] = \"MAPE\"\n#kable(maepe_table, format=\"pipe\")\n```\n\n```{r}\n#create plot of rdius vs weight in test data\n#plot(x=banana_test$radius, y = banana_test$weight, type='p', col='red')\n\n#overlay line plot of radius vs predicted weight by linfit_r\n#lines(banana_test$radius, exp(pred.r), col='blue')\n\n#overlay line plot of radius vs predicted by fitr_wi\n#lines(banana_test$radius, exp(pred.rw8), col='purple')\n\n#add legend\n#legend(1, 25, legend=c('actual', 'linfit_r', 'fitr_wi'),\n#       col=c('red', 'blue', 'purple'), lty=1)\n```\n\n```{r, linewidth=60}\n#bweight_df = data.frame(banana_test$radius, \n#banana_test$weight, \n#exp(pred.r),exp(pred.rwi))\n#print(bweight_df)\n```\n\n```{r}\n# confidence interval for the density\n# density is in the intercept (beta_0) term of linfit_full\nb0_full = linfit_full$coefficients[1]\n# st error of intercept in linfit_full: 49.39822\nq.se = qnorm(1-(0.05/2))*49.39822\nconfidence_i = (pred.rwi / pred.r)+c(-1,1)*0.008949\nmin(confidence_i)\nmax(confidence_i)\n\nconfidence_i2 = (pred.rwi / pred.r)+c(-1,1)*0.5986\nabs(min(confidence_i2))\nabs(max(confidence_i2))\n```\n\n\n## References \n\n[1]  “13.1 - weighted least squares: Stat 501,” PennState: Statistics Online Courses. [Online]. Available: https://online.stat.psu.edu/stat501/lesson/13/13.1. [Accessed: 06-Feb-2022].  \n\n\n\n\n# Project 2\n---\ntitle: \"Calibrating Snow Gauge\"\nauthor: \"Iza\"\ndate: \"3/24/2022\"\noutput: html_document\n---\n\n```{r setup, include=FALSE}\nknitr::opts_chunk$set(echo = TRUE)\n```\n\n## the data\n```{r}\nDensity = c(0.686,0.604,0.508,0.412,\n            0.318,0.223,0.148,0.080,0.001)\n\nGain1 = c(17.6,24.8,39.4,60.0,\n          87.0,128,199,298,423)\nGain2 = c(17.3,25.9,37.6,58.3,\n          92.7,130,204,298,421)\nGain3 = c(16.9,26.3,38.1,59.6,\n          90.5,131,199,297,422)\nGain4 = c(16.2,24.8,37.7,59.1,\n          85.8,129,207,288,428)\nGain5 = c(17.1,24.8,36.3,56.3,\n          87.5,127,200,296,436)\nGain6 = c(18.5,27.6,38.7,55.0,\n          88.3,129,200,293,427)\nGain7 = c(18.7,28.5,39.4,52.9,\n          91.6,132,205,301,426)\nGain8 = c(17.4,30.5,38.8,54.1,\n          88.2,133,202,299,428)\nGain9 = c(18.6,28.4,39.2,56.9,\n          88.6,134,199,298,427)\nGain10 = c(16.8,27.7,40.3,56.0,\n           84.7,133,199,293,429)\n\n#df with only two columns\ndf1 = data.frame(\n  rep(Density,10),\n  c(Gain1,Gain2,Gain3,Gain4,Gain5,\n    Gain6,Gain7,Gain8,Gain9,Gain10))\n#chage column names\nnames(df1) = c(\"Density\",\"Gain\")\n\n```\n\n## How are density and gain related?\n```{r}\nlibrary(ggplot2)\n\ndxg = ggplot(df1,aes(x=Density, y =Gain))\ndxg_df1 = dxg + ggtitle(\"Point Plot each Polyethylene Density and its 10 Gains reading\") + geom_point(aes(colour = factor(Density)))\n```\n\n# Relationship of Gain and Density\n$Gain = e^{b*Density}$ or $ln(Gain) = b*Density$\n\n\n# model 0: just a linear \n```{r}\nmodel0 = lm(Gain~Density, data=df1)\nsummary(model0)\ncoefs1 = model0$coefficients\nplot(model0)\n```\n\n\n\n# Model fitting using trasformation and linear regression\nIn order to use \"lm()\" we have to make the relationship between the two variables to be linear. Hence the log transformation of the Gain variable.\n```{r}\nmodel1 = lm(log(Gain)~Density, data=df1)\nsummary(model1)\ncoefs1 = model1$coefficients\nplot(model1)\n```\n\n# the physical model representin\n$$Gain = e^{b*Density}$$\n$$log(Gain) = b*Density$$\nusing the data, the model with coefficients is\n$$log(Gain) = b*Density + a + \\epsilon$$\n\n,where $b = -4.60594$ and $a = 5.99727$. \n\nIf apply exponent\n$$Gain = e^{b*Density + a} = e^{b*Density} *e^{a}$$\n\n# Predict the Density using the models\n\n\n```{r}\n# without error term\n# predict Gains using model1\n#G.pred1 = exp(predict(model1, df1, level=0.95, interval=\"confidence\"))\n\n# but we want density, inverse estimating... using the equation of the model\nD.pred1 = (log(df1$Gain) - model1$coefficients[1]) /  model1$coefficients[2]\n# notice that they give the same point estimates of density\n\nnum = (D.pred1 - mean(df1$Gain))^2\ndenom = sum((df1$Gain - mean(df1$Gain))^2)\n\nn = nrow(df1)\ns.hat = 0.06792 # is this value right?\nlowerb = D.pred1-(qnorm(0.975)*s.hat*sqrt((1/n) + num/denom))\nupperb = D.pred1+(qnorm(0.975)*s.hat*sqrt((1/n) + num/denom))\n\nlowerb \u003c df1$Density \u0026 df1$Density \u003c upperb\ntable(lowerb \u003c df1$Density \u0026 df1$Density \u003c upperb)\n\n\nD.pred1.pt = (log(df1$Gain) - model1$coefficients[1] - model1$residuals) /  model1$coefficients[2]\nlowerb.pt = D.pred1.pt - (qnorm(0.975)*s.hat*sqrt((1/n) + num/denom))\nupperb.pt = D.pred1.pt + (qnorm(0.975)*s.hat*sqrt((1/n) + num/denom))\ntable(lowerb.pt \u003c df1$Density \u0026 df1$Density \u003c upperb.pt)\n# with error term, all the interval estimates encompass all obs. densities\n\n```\n\n\n\n#plotting model1\n$$Gain = c* e^{b*Density},$$\nwhere $c = e^{a}$, $b = -4.60594$ and $a = 5.99727$.\n\\\n```{r}\n\nfunc = function(x){\n  exp(model1$coefficients[2]*x)*exp(model1$coefficients[1])\n}\ndxg_df1\ndxg_df1 + geom_function(fun =func) \n```\n\n\n\n# modelling without extreme cases\n\n## model2 - same as model1 but 0.001 density data removed from training set\n```{r}\ndf2 = subset(df1, Density!= 0.001)\n#model without 0.001\nmodel2.l = lm(log(Gain)~Density, data=df2)\nsummary(model2.l)\ncoefs2.l = model2.l$coefficients\n#plot(model2.l)\n\n# but we want density\nD.pred2.l = (log(df2$Gain) - model2.l$coefficients[1]) /  model2.l$coefficients[2]\n# notice that they give the same point estimates of density\n\nnum2.l = (D.pred2.l - mean(df2$Gain))^2\ndenom2.l = sum((df2$Gain - mean(df2$Gain))^2)\n\nn2.l = nrow(df2)\ns.hat2.l = 0.0694 # is this value right?\nlowerb2.l = D.pred2.l-(qnorm(0.975)*s.hat2.l*sqrt((1/n2.l) + num2.l/denom2.l))\nupperb2.l = D.pred2.l+(qnorm(0.975)*s.hat2.l*sqrt((1/n2.l) + num2.l/denom2.l))\n\n#check if observed density is within the interval\ntable(lowerb2.l \u003c df2$Density \u0026 df2$Density \u003c upperb2.l)\n\n\n#predicting point est of density with error term\nD.pred2.l.pt = (log(df2$Gain) - model2.b$coefficients[1] - model2.l$residuals) /  model2.b$coefficients[2]\nlowerb2.l.pt = D.pred2.l.pt-(qnorm(0.975)*s.hat2.l*sqrt((1/n2.l) + num2.l/denom2.l))\nupperb2.l.pt = D.pred2.l.pt+(qnorm(0.975)*s.hat2.l*sqrt((1/n2.l) + num2.l/denom2.l))\n\ntable(lowerb2.l.pt \u003c df2$Density \u0026 df2$Density \u003c upperb2.l.pt)\n\n# with error term, all the interval estimates encompass all obs. densities\n\n```\n#model3 - same techniques as model1 but with 0.686 density data removed from training set\n```{r}\ndf3 = subset(df1,  Density!= 0.686)\n#model without 0.686\nmodel2.u = lm(log(Gain)~Density, data=df3)\nsummary(model2.u)\ncoefs2.u = model2.u$coefficients\n#plot(model2.u)\n\n# but we want density\nD.pred2.u = (log(df3$Gain) - model2.u$coefficients[1]) /  model2.u$coefficients[2]\n# notice that they give the same point estimates of density\n\nnum2.u = (D.pred2.u - mean(df3$Gain))^2\ndenom2.u = sum((df3$Gain - mean(df3$Gain))^2)\nn2.u = nrow(df3)\ns.hat2.u = 0.06633 # is this value right?\nlowerb2.u = D.pred2.u-(qnorm(0.975, nrow(df3)-2)*s.hat2.u*sqrt(1+ (1/n2.u) + num2.u/denom2.u))\nupperb2.u = D.pred2.u+(qnorm(0.975, nrow(df3)-2)*s.hat2.u*sqrt(1+(1/n2.u) + num2.u/denom2.u))\n\nlowerb2.u \u003c df3$Density \u0026 df3$Density \u003c upperb2.u\ntable(lowerb2.u \u003c df3$Density \u0026 df3$Density \u003c upperb2.u)\n\n#predicting density with error term\nD.pred2.u.pt=(log(df3$Gain) - model2.b$coefficients[1] - model2.u$residuals) /  model2.b$coefficients[2]\nlowerb2.u.pt = D.pred2.u.pt-(qt(0.975, nrow(df3)-2)*s.hat2.u*sqrt(1+(1/n2.u) + num2.u/denom2.u))\nupperb2.u.pt = D.pred2.u.pt+(qt(0.975, nrow(df3)-2)*s.hat2.u*sqrt(1+(1/n2.u) + num2.u/denom2.u))\ntable(lowerb2.u.pt \u003c df3$Density \u0026 df3$Density \u003c upperb2.u.pt)\n# with error term, all the interval estimates encompass all obs. densities\n\n```\n\n#model4 - same techniques as model1 but both 0.001 0.686 density data removed from training set\n```{r}\ndf4 = subset(df1,  Density\u003e0.001 \u0026 Density\u003c0.686)\n\n#model without 0.686 and 0.001\nmodel2.b = lm(log(Gain)~Density, data=df4)\nsummary(model2.b)\ncoefs2.b = model2.b$coefficients\n#plot(model2.b)\n\n# but we want density\nD.pred2.b = (log(df4$Gain) - model2.b$coefficients[1]) /  model2.b$coefficients[2]\n\n\n\nnum2.b = (D.pred2.b - mean(df4$Gain))^2\ndenom2.b = sum((df4$Gain - mean(df4$Gain))^2)\nn2.b = nrow(df4)\ns.hat2.b = 0.06868 # is this value right?\nlowerb2.b = D.pred2.b-(qt(0.975,df = nrow(df4)-2)*s.hat2.b*sqrt((1/n2.b) + num2.b/denom2.b))\nupperb2.b = D.pred2.b+(qt(0.975, df = nrow(df4)-2)*s.hat2.b*sqrt((1/n2.b) + num2.b/denom2.b))\n\nlowerb2.b \u003c df4$Density \u0026 df4$Density \u003c upperb2.b\ntable(lowerb2.b \u003c df4$Density \u0026 df4$Density \u003c upperb2.b)\n\n#predicting density with error term\nD.pred2.b.pt = (log(df4$Gain) - model2.b$coefficients[1] - model2.b$residuals) /  model2.b$coefficients[2]\nlowerb2.b.pt = D.pred2.b.pt-(qnorm(0.975)*s.hat2.b*sqrt((1/n2.b) + num2.b/denom2.b))\nupperb2.b.pt = D.pred2.b.pt+(qnorm(0.975)*s.hat2.b*sqrt((1/n2.b) + num2.b/denom2.b))\ntable(lowerb2.b.pt \u003c df4$Density \u0026 df4$Density \u003c upperb2.b.pt)\n# with error term, all the interval estimates encompass all obs. densities\n\n```\n\n# error\ntruth = reported value + measurement error\n```{r}\ne= model1$residuals\nqqnorm(e)\nqqline(e)\nshapiro.test(e)\n# residuals are normally distributed\ndf1$Density \n```\n# confidence interval of Density estimate by model\n```{r}\n# function to find lower and upper bounds for a model\nCI = function(model, alpha){\n  if(model == 1){\n    num = (D.pred1 - mean(df1$Gain))^2\n    denom = sum((df1$Gain - mean(df1$Gain))^2)\n    n = nrow(df1)\n    s.hat = 0.06792 # is this value right?\n    lowerb = D.pred1-(qnorm(1-(alpha/2))*s.hat*sqrt((1/n) + num/denom))\n    upperb = D.pred1+(qnorm(1-(alpha/2))*s.hat*sqrt((1/n) + num/denom))\n  }\n  else if(model==2){\n    num2.l = (D.pred2.l - mean(df2$Gain))^2\n    denom2.l = sum((df2$Gain - mean(df2$Gain))^2)\n    n2.l = nrow(df2)\n    s.hat2.l = 0.0694 # is this value right?\n    lowerb = D.pred2.l-(qnorm(alpha/2)*s.hat2.l*sqrt((1/n2.l) + num2.l/denom2.l))\n    upperb = D.pred2.l+(qnorm(alpha/2)*s.hat2.l*sqrt((1/n2.l) + num2.l/denom2.l))\n  }\n  else if(model==3){\n    num2.u = (D.pred2.u - mean(df3$Gain))^2\n    denom2.u = sum((df3$Gain - mean(df3$Gain))^2)\n    n2.u = nrow(df3)\n    s.hat2.u = 0.06633 # is this value right?\n    lowerb = D.pred2.u-(qnorm(alpha/2)*s.hat2.u*sqrt((1/n2.u) + num2.u/denom2.u))\n    upperb = D.pred2.u+(qnorm(alpha/2)*s.hat2.u*sqrt((1/n2.u) + num2.u/denom2.u))\n  }\n  else if(model==4){\n    num2.b = (D.pred2.b - mean(df4$Gain))^2\n    denom2.b = sum((df4$Gain - mean(df4$Gain))^2)\n    n2.b = nrow(df4)\n    s.hat2.b = 0.06868 # is this value right?\n    lowerb = D.pred2.b-(qnorm(alpha/2)*s.hat2.b*sqrt((1/n2.b) + num2.b/denom2.b))\n    upperb = D.pred2.b+(qnorm(alpha/2)*s.hat2.b*sqrt((1/n2.b) + num2.b/denom2.b))\n  }\n  else{\n    print(\"model not found...\")\n    lowerb = NA\n    upperb = NA\n  }\n  return(as.data.frame(cbind(lowerb,upperb)))\n}\n\n# 95% confidence interval of model1\nCI(1,0.05)\n\n# 95% confidence interval of model2.l \n# note: model2.l has log(Gain) as y and Density as x; data with low density:0.001 is removed \nCI(2,0.05)\n\n# 95% confidence interval of model2.u\n# note: model2.u has log(Gain) as y and Density as x; data with high density:0.686 is removed \nCI(3,0.05)\n\n# 95% confidence interval of model2.b\n# note: model2.b has log(Gain) as y and Density as x; both low density:0.001 and 0.686 are removed \nCI(4,0.05)\n```\n\n# Given a gain, what is it's estimated density and its interval, depending on the model used?\n```{r}\nestimateDensity = function(gain, model, alpha){\n  if(model==1){\n    pointEstimate = (log(gain) - model1$coefficients[1]) /  model1$coefficients[2]\n    num = (pointEstimate - mean(df1$Gain))^2\n    denom = sum((df1$Gain - mean(df1$Gain))^2)\n    n = nrow(df1)\n    s.hat = 0.06792 # is this value right?\n    ci = pointEstimate + c(-1,1)*(qt(1-(alpha/2), nrow(df1)-2)*s.hat*sqrt(1+ (1/n) + num/denom))\n  }\n  else if(model==2){\n    pointEstimate = (log(gain) - model2.l$coefficients[1]) /  model2.l$coefficients[2]\n    num2.l = (pointEstimate - mean(df2$Gain))^2\n    denom2.l = sum((df2$Gain - mean(df2$Gain))^2)\n    n2.l = nrow(df2)\n    s.hat2.l = 0.0694 # is this value right?\n    ci = pointEstimate + c(-1,1)*(qt(1-(alpha/2), nrow(df2)-2)*s.hat2.l*sqrt(1+ (1/n2.l) + num2.l/denom2.l))\n    \n  }\n  else if(model==3){\n    pointEstimate = (log(gain) - model2.u$coefficients[1]) /  model2.u$coefficients[2]\n    num2.u = (pointEstimate - mean(df3$Gain))^2\n    denom2.u = sum((df3$Gain - mean(df3$Gain))^2)\n    n2.u = nrow(df3)\n    s.hat2.u = 0.06633 # is this value right?\n    ci = pointEstimate + c(-1,1)*(qt(1-(alpha/2), nrow(df3)-2)*s.hat2.u*sqrt(1+ (1/n2.u) + num2.u/denom2.u))\n  }\n  else if(model==4){\n    pointEstimate = (log(gain) - model2.b$coefficients[1]) /  model2.b$coefficients[2]\n    num2.b = (pointEstimate - mean(df4$Gain))^2\n    denom2.b = sum((df4$Gain - mean(df4$Gain))^2)\n    n2.b = nrow(df4)\n    s.hat2.b = 0.06868 # is this value right?\n    ci = pointEstimate + c(-1,1)*(qt(1-(alpha/2), nrow(df4)-2)*s.hat2.b*sqrt(1+(1/n2.b) + num2.b/denom2.b))\n    \n  }\n  else{\n    print(\"model not found...\")\n    pointEstimate = NA\n    ci = NA\n  }\n  \n  df = data.frame(cbind(\n    rep(c(\"point estimate \", \"lowerb\",\"upperb\"),length(gain)),\n    c(pointEstimate, ci)))\n  names(df) = c(\"label\", \"value\")\n  return(df)\n}\n```\n\n\n/plot the conf intervals for each model\n\n```{r}\n# put model type: 1,2,3,4, gains, fit.value of density and their, se.fit. in a df then add on the plot\n\nm1 = rep(1, length(D.pred1))\nm2 = rep(2, length(D.pred2.l))\nm3 = rep(3, length(D.pred2.u))\nm4 = rep(4, length(D.pred2.b))\nmodel = c(m1,m2,m3,m4)\np.estimates = c(D.pred1, D.pred2.l, D.pred2.u, D.pred2.b)\nest.df = data.frame(model,p.estimates)\n\nfunc = function(x){\n  exp(model1$coefficients[2]*x)*exp(model1$coefficients[1])\n}\ndxg_df1\ndxg_df1 + geom_function(fun =func) \n```\n\n\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fizalu99%2Fpast-project-reports","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fizalu99%2Fpast-project-reports","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fizalu99%2Fpast-project-reports/lists"}