From 0b48cc3391f976e9911b5f91e3f59719ab423d11 Mon Sep 17 00:00:00 2001 From: Michaja Pehl Date: Fri, 25 Oct 2019 16:44:56 +0200 Subject: [PATCH] renormalise and set gitattributes to get rid of CRLF issues --- .gitattributes | 2 + DESCRIPTION | 56 +- LICENSE | 330 +++++----- NAMESPACE | 86 +-- R/calcCollectRegressionData.R | 838 ++++++++++++------------ R/mrrgression-package.R | 36 +- R/nlsAddLines.R | 108 ++-- R/nlsregression.R | 998 ++++++++++++++--------------- R/robust_vce.R | 26 +- R/toolCollectRegressionVariables.R | 346 +++++----- R/toolRegression.R | 314 ++++----- R/toolRegressionTable.R | 272 ++++---- mrregression.Rproj | 36 +- 13 files changed, 1725 insertions(+), 1723 deletions(-) create mode 100644 .gitattributes diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..fe9db41 --- /dev/null +++ b/.gitattributes @@ -0,0 +1,2 @@ +* text=auto + diff --git a/DESCRIPTION b/DESCRIPTION index bab70c2..c50f917 100644 --- a/DESCRIPTION +++ b/DESCRIPTION @@ -1,28 +1,28 @@ -Package: mrregression -Type: Package -Title: Regression analysis for model parametrization -Version: 3.12.3 -Date: 2019-05-29 -Author: Benjamin Leon Bodirsky, Antonia Walther, Xiaoxi Wang, Abhijeet Mishra, Eleonora Martinelli -Maintainer: Benjamin Leon Bodirsky -Description: Model estimates parameters of model functions. -Depends: - R(>= 2.10.0), - magclass(>= 3.17), - madrat(>= 1.28), - moinput(>= 8.145), - magpiesets(>= 0.27) -Imports: - stats, - lmtest, - sandwich, - graphics, - countrycode, - RColorBrewer, - boot, - nlstools -License: LGPL-3 | file LICENSE -LazyData: no -RoxygenNote: 6.1.1 -ValidationKey: 56354535 -Encoding: UTF-8 +Package: mrregression +Type: Package +Title: Regression analysis for model parametrization +Version: 3.12.3 +Date: 2019-05-29 +Author: Benjamin Leon Bodirsky, Antonia Walther, Xiaoxi Wang, Abhijeet Mishra, Eleonora Martinelli +Maintainer: Benjamin Leon Bodirsky +Description: Model estimates parameters of model functions. +Depends: + R(>= 2.10.0), + magclass(>= 3.17), + madrat(>= 1.28), + moinput(>= 8.145), + magpiesets(>= 0.27) +Imports: + stats, + lmtest, + sandwich, + graphics, + countrycode, + RColorBrewer, + boot, + nlstools +License: LGPL-3 | file LICENSE +LazyData: no +RoxygenNote: 6.1.1 +ValidationKey: 56354535 +Encoding: UTF-8 diff --git a/LICENSE b/LICENSE index b14ca0a..65c5ca8 100644 --- a/LICENSE +++ b/LICENSE @@ -1,165 +1,165 @@ - GNU LESSER GENERAL PUBLIC LICENSE - Version 3, 29 June 2007 - - Copyright (C) 2007 Free Software Foundation, Inc. - Everyone is permitted to copy and distribute verbatim copies - of this license document, but changing it is not allowed. - - - This version of the GNU Lesser General Public License incorporates -the terms and conditions of version 3 of the GNU General Public -License, supplemented by the additional permissions listed below. - - 0. Additional Definitions. - - As used herein, "this License" refers to version 3 of the GNU Lesser -General Public License, and the "GNU GPL" refers to version 3 of the GNU -General Public License. - - "The Library" refers to a covered work governed by this License, -other than an Application or a Combined Work as defined below. - - An "Application" is any work that makes use of an interface provided -by the Library, but which is not otherwise based on the Library. -Defining a subclass of a class defined by the Library is deemed a mode -of using an interface provided by the Library. - - A "Combined Work" is a work produced by combining or linking an -Application with the Library. The particular version of the Library -with which the Combined Work was made is also called the "Linked -Version". - - The "Minimal Corresponding Source" for a Combined Work means the -Corresponding Source for the Combined Work, excluding any source code -for portions of the Combined Work that, considered in isolation, are -based on the Application, and not on the Linked Version. - - The "Corresponding Application Code" for a Combined Work means the -object code and/or source code for the Application, including any data -and utility programs needed for reproducing the Combined Work from the -Application, but excluding the System Libraries of the Combined Work. - - 1. Exception to Section 3 of the GNU GPL. - - You may convey a covered work under sections 3 and 4 of this License -without being bound by section 3 of the GNU GPL. - - 2. Conveying Modified Versions. - - If you modify a copy of the Library, and, in your modifications, a -facility refers to a function or data to be supplied by an Application -that uses the facility (other than as an argument passed when the -facility is invoked), then you may convey a copy of the modified -version: - - a) under this License, provided that you make a good faith effort to - ensure that, in the event an Application does not supply the - function or data, the facility still operates, and performs - whatever part of its purpose remains meaningful, or - - b) under the GNU GPL, with none of the additional permissions of - this License applicable to that copy. - - 3. Object Code Incorporating Material from Library Header Files. - - The object code form of an Application may incorporate material from -a header file that is part of the Library. You may convey such object -code under terms of your choice, provided that, if the incorporated -material is not limited to numerical parameters, data structure -layouts and accessors, or small macros, inline functions and templates -(ten or fewer lines in length), you do both of the following: - - a) Give prominent notice with each copy of the object code that the - Library is used in it and that the Library and its use are - covered by this License. - - b) Accompany the object code with a copy of the GNU GPL and this license - document. - - 4. Combined Works. - - You may convey a Combined Work under terms of your choice that, -taken together, effectively do not restrict modification of the -portions of the Library contained in the Combined Work and reverse -engineering for debugging such modifications, if you also do each of -the following: - - a) Give prominent notice with each copy of the Combined Work that - the Library is used in it and that the Library and its use are - covered by this License. - - b) Accompany the Combined Work with a copy of the GNU GPL and this license - document. - - c) For a Combined Work that displays copyright notices during - execution, include the copyright notice for the Library among - these notices, as well as a reference directing the user to the - copies of the GNU GPL and this license document. - - d) Do one of the following: - - 0) Convey the Minimal Corresponding Source under the terms of this - License, and the Corresponding Application Code in a form - suitable for, and under terms that permit, the user to - recombine or relink the Application with a modified version of - the Linked Version to produce a modified Combined Work, in the - manner specified by section 6 of the GNU GPL for conveying - Corresponding Source. - - 1) Use a suitable shared library mechanism for linking with the - Library. A suitable mechanism is one that (a) uses at run time - a copy of the Library already present on the user's computer - system, and (b) will operate properly with a modified version - of the Library that is interface-compatible with the Linked - Version. - - e) Provide Installation Information, but only if you would otherwise - be required to provide such information under section 6 of the - GNU GPL, and only to the extent that such information is - necessary to install and execute a modified version of the - Combined Work produced by recombining or relinking the - Application with a modified version of the Linked Version. (If - you use option 4d0, the Installation Information must accompany - the Minimal Corresponding Source and Corresponding Application - Code. If you use option 4d1, you must provide the Installation - Information in the manner specified by section 6 of the GNU GPL - for conveying Corresponding Source.) - - 5. Combined Libraries. - - You may place library facilities that are a work based on the -Library side by side in a single library together with other library -facilities that are not Applications and are not covered by this -License, and convey such a combined library under terms of your -choice, if you do both of the following: - - a) Accompany the combined library with a copy of the same work based - on the Library, uncombined with any other library facilities, - conveyed under the terms of this License. - - b) Give prominent notice with the combined library that part of it - is a work based on the Library, and explaining where to find the - accompanying uncombined form of the same work. - - 6. Revised Versions of the GNU Lesser General Public License. - - The Free Software Foundation may publish revised and/or new versions -of the GNU Lesser General Public License from time to time. Such new -versions will be similar in spirit to the present version, but may -differ in detail to address new problems or concerns. - - Each version is given a distinguishing version number. If the -Library as you received it specifies that a certain numbered version -of the GNU Lesser General Public License "or any later version" -applies to it, you have the option of following the terms and -conditions either of that published version or of any later version -published by the Free Software Foundation. If the Library as you -received it does not specify a version number of the GNU Lesser -General Public License, you may choose any version of the GNU Lesser -General Public License ever published by the Free Software Foundation. - - If the Library as you received it specifies that a proxy can decide -whether future versions of the GNU Lesser General Public License shall -apply, that proxy's public statement of acceptance of any version is -permanent authorization for you to choose that version for the -Library. + GNU LESSER GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + + This version of the GNU Lesser General Public License incorporates +the terms and conditions of version 3 of the GNU General Public +License, supplemented by the additional permissions listed below. + + 0. Additional Definitions. + + As used herein, "this License" refers to version 3 of the GNU Lesser +General Public License, and the "GNU GPL" refers to version 3 of the GNU +General Public License. + + "The Library" refers to a covered work governed by this License, +other than an Application or a Combined Work as defined below. + + An "Application" is any work that makes use of an interface provided +by the Library, but which is not otherwise based on the Library. +Defining a subclass of a class defined by the Library is deemed a mode +of using an interface provided by the Library. + + A "Combined Work" is a work produced by combining or linking an +Application with the Library. The particular version of the Library +with which the Combined Work was made is also called the "Linked +Version". + + The "Minimal Corresponding Source" for a Combined Work means the +Corresponding Source for the Combined Work, excluding any source code +for portions of the Combined Work that, considered in isolation, are +based on the Application, and not on the Linked Version. + + The "Corresponding Application Code" for a Combined Work means the +object code and/or source code for the Application, including any data +and utility programs needed for reproducing the Combined Work from the +Application, but excluding the System Libraries of the Combined Work. + + 1. Exception to Section 3 of the GNU GPL. + + You may convey a covered work under sections 3 and 4 of this License +without being bound by section 3 of the GNU GPL. + + 2. Conveying Modified Versions. + + If you modify a copy of the Library, and, in your modifications, a +facility refers to a function or data to be supplied by an Application +that uses the facility (other than as an argument passed when the +facility is invoked), then you may convey a copy of the modified +version: + + a) under this License, provided that you make a good faith effort to + ensure that, in the event an Application does not supply the + function or data, the facility still operates, and performs + whatever part of its purpose remains meaningful, or + + b) under the GNU GPL, with none of the additional permissions of + this License applicable to that copy. + + 3. Object Code Incorporating Material from Library Header Files. + + The object code form of an Application may incorporate material from +a header file that is part of the Library. You may convey such object +code under terms of your choice, provided that, if the incorporated +material is not limited to numerical parameters, data structure +layouts and accessors, or small macros, inline functions and templates +(ten or fewer lines in length), you do both of the following: + + a) Give prominent notice with each copy of the object code that the + Library is used in it and that the Library and its use are + covered by this License. + + b) Accompany the object code with a copy of the GNU GPL and this license + document. + + 4. Combined Works. + + You may convey a Combined Work under terms of your choice that, +taken together, effectively do not restrict modification of the +portions of the Library contained in the Combined Work and reverse +engineering for debugging such modifications, if you also do each of +the following: + + a) Give prominent notice with each copy of the Combined Work that + the Library is used in it and that the Library and its use are + covered by this License. + + b) Accompany the Combined Work with a copy of the GNU GPL and this license + document. + + c) For a Combined Work that displays copyright notices during + execution, include the copyright notice for the Library among + these notices, as well as a reference directing the user to the + copies of the GNU GPL and this license document. + + d) Do one of the following: + + 0) Convey the Minimal Corresponding Source under the terms of this + License, and the Corresponding Application Code in a form + suitable for, and under terms that permit, the user to + recombine or relink the Application with a modified version of + the Linked Version to produce a modified Combined Work, in the + manner specified by section 6 of the GNU GPL for conveying + Corresponding Source. + + 1) Use a suitable shared library mechanism for linking with the + Library. A suitable mechanism is one that (a) uses at run time + a copy of the Library already present on the user's computer + system, and (b) will operate properly with a modified version + of the Library that is interface-compatible with the Linked + Version. + + e) Provide Installation Information, but only if you would otherwise + be required to provide such information under section 6 of the + GNU GPL, and only to the extent that such information is + necessary to install and execute a modified version of the + Combined Work produced by recombining or relinking the + Application with a modified version of the Linked Version. (If + you use option 4d0, the Installation Information must accompany + the Minimal Corresponding Source and Corresponding Application + Code. If you use option 4d1, you must provide the Installation + Information in the manner specified by section 6 of the GNU GPL + for conveying Corresponding Source.) + + 5. Combined Libraries. + + You may place library facilities that are a work based on the +Library side by side in a single library together with other library +facilities that are not Applications and are not covered by this +License, and convey such a combined library under terms of your +choice, if you do both of the following: + + a) Accompany the combined library with a copy of the same work based + on the Library, uncombined with any other library facilities, + conveyed under the terms of this License. + + b) Give prominent notice with the combined library that part of it + is a work based on the Library, and explaining where to find the + accompanying uncombined form of the same work. + + 6. Revised Versions of the GNU Lesser General Public License. + + The Free Software Foundation may publish revised and/or new versions +of the GNU Lesser General Public License from time to time. Such new +versions will be similar in spirit to the present version, but may +differ in detail to address new problems or concerns. + + Each version is given a distinguishing version number. If the +Library as you received it specifies that a certain numbered version +of the GNU Lesser General Public License "or any later version" +applies to it, you have the option of following the terms and +conditions either of that published version or of any later version +published by the Free Software Foundation. If the Library as you +received it does not specify a version number of the GNU Lesser +General Public License, you may choose any version of the GNU Lesser +General Public License ever published by the Free Software Foundation. + + If the Library as you received it specifies that a proxy can decide +whether future versions of the GNU Lesser General Public License shall +apply, that proxy's public statement of acceptance of any version is +permanent authorization for you to choose that version for the +Library. diff --git a/NAMESPACE b/NAMESPACE index 5db82d8..eecd376 100644 --- a/NAMESPACE +++ b/NAMESPACE @@ -1,43 +1,43 @@ -# Generated by roxygen2: do not edit by hand - -export(calcCollectRegressionData) -export(nlsAddLines) -export(nlsregression) -export(robust_vce) -export(toolCollectRegressionVariables) -export(toolRegression) -export(toolRegressionTable) -import(madrat) -import(magclass) -import(utils) -importFrom(RColorBrewer,brewer.pal) -importFrom(RColorBrewer,brewer.pal.info) -importFrom(boot,corr) -importFrom(countrycode,countrycode) -importFrom(grDevices,colorRampPalette) -importFrom(graphics,abline) -importFrom(graphics,curve) -importFrom(graphics,legend) -importFrom(graphics,lines) -importFrom(graphics,plot) -importFrom(graphics,points) -importFrom(graphics,text) -importFrom(lmtest,bptest) -importFrom(lmtest,coeftest) -importFrom(madrat,vcat) -importFrom(magpiesets,findset) -importFrom(moinput,toolFAOcombine) -importFrom(nlstools,confint2) -importFrom(sandwich,sandwich) -importFrom(stats,as.formula) -importFrom(stats,cor) -importFrom(stats,lm) -importFrom(stats,logLik) -importFrom(stats,nls) -importFrom(stats,predict) -importFrom(stats,quantile) -importFrom(stats,resid) -importFrom(stats,shapiro.test) -importFrom(stats,var) -importFrom(stats,weighted.mean) -importFrom(stats,weights) +# Generated by roxygen2: do not edit by hand + +export(calcCollectRegressionData) +export(nlsAddLines) +export(nlsregression) +export(robust_vce) +export(toolCollectRegressionVariables) +export(toolRegression) +export(toolRegressionTable) +import(madrat) +import(magclass) +import(utils) +importFrom(RColorBrewer,brewer.pal) +importFrom(RColorBrewer,brewer.pal.info) +importFrom(boot,corr) +importFrom(countrycode,countrycode) +importFrom(grDevices,colorRampPalette) +importFrom(graphics,abline) +importFrom(graphics,curve) +importFrom(graphics,legend) +importFrom(graphics,lines) +importFrom(graphics,plot) +importFrom(graphics,points) +importFrom(graphics,text) +importFrom(lmtest,bptest) +importFrom(lmtest,coeftest) +importFrom(madrat,vcat) +importFrom(magpiesets,findset) +importFrom(moinput,toolFAOcombine) +importFrom(nlstools,confint2) +importFrom(sandwich,sandwich) +importFrom(stats,as.formula) +importFrom(stats,cor) +importFrom(stats,lm) +importFrom(stats,logLik) +importFrom(stats,nls) +importFrom(stats,predict) +importFrom(stats,quantile) +importFrom(stats,resid) +importFrom(stats,shapiro.test) +importFrom(stats,var) +importFrom(stats,weighted.mean) +importFrom(stats,weights) diff --git a/R/calcCollectRegressionData.R b/R/calcCollectRegressionData.R index 2eaefba..a4fc2a5 100644 --- a/R/calcCollectRegressionData.R +++ b/R/calcCollectRegressionData.R @@ -1,419 +1,419 @@ -#' @title calcCollectRegressionData -#' @description collects regression data using un-converted raw data sources, and crops the data that only joint years and countries are selected. -#' -#' @param datasources All datasources that shall be returned. Due to the cropping of data which is not present in all datasources, reducing the number of datasources will increase the number of observations. -#' @return List of magpie objects with results on country level, weight on country level, unit and description. -#' @author Benjamin Leon Bodirsky, Eleonora Martinelli, Abhijeet Mishra, Xiaoxi Wang -#' @examples -#' -#' \dontrun{ -#' calcOutput("CollectRegressionData",aggregate=F) -#' } -#' - -#' @importFrom countrycode countrycode -#' @importFrom magpiesets findset -#' @importFrom moinput toolFAOcombine -#' @importFrom stats quantile -#' @import magclass -#' @import madrat -#' @export - -calcCollectRegressionData <- function(datasources) - { - combined<-list() - - if ("wooddemand" %in% datasources) { - wooddemand <- calcOutput("FAOForestryDemand",aggregate = FALSE) - roundwood <- wooddemand[,,"roundwood.domestic_supply"] - roundwood <- setNames(roundwood,c("roundwood")) - - wood <- wooddemand[,,"wood.domestic_supply"] - wood <- setNames(wood,c("wood")) - - woodfuel <- wooddemand[,,"woodfuel.domestic_supply"] - woodfuel <- setNames(woodfuel,c("woodfuel")) - - wooddemand <- mbind(roundwood,wood,woodfuel) - wooddemand <- wooddemand[,sort(getYears(wooddemand)),] - wooddemand <- wooddemand[which(!is.na(dimnames(wooddemand)[[1]])),,] - wooddemand[c("TWN","AIA","NRU","VGB","KWT","COK"),,] <- 0 - - wooddemand[,,"woodfuel"] <- wooddemand[,,"woodfuel"]*1000/632.5 ## mio.m3 - wooddemand[,,"wood"] <- wooddemand[,,"wood"]*1000/307.1 ## mio.m3 - combined$wooddemand<-wooddemand - } - - if ("SelfSuff" %in% datasources) { - SelfSuff_w <- calcOutput("TradeSelfSuff",convert = F)[,,"wood"] - SelfSuff_wf <- calcOutput("TradeSelfSuff",convert = F)[,,"woodfuel"] - SelfSuff <- mbind(SelfSuff_w,SelfSuff_wf) - SelfSuff <- SelfSuff[,sort(getYears(SelfSuff)),] - SelfSuff <- SelfSuff[which(!is.na(dimnames(SelfSuff)[[1]])),,] - getNames(SelfSuff) <- paste0("ss_",getNames(SelfSuff)) - combined$SelfSuff<-SelfSuff - } - - if ("timber_demand" %in% datasources) { - timber_demand <- collapseNames(calcOutput("TimberDemand",aggregate = FALSE)[,,"domestic_supply"]) - combined$forestry<-timber_demand - } - - if ("forest_area" %in% datasources) { - FA_LUI <- calcOutput("LanduseInitialisation",aggregate = FALSE) - - forest_area <- dimSums(FA_LUI[,,c("forestry","primforest","secdforest")],dim=3) - forest_area <- setNames(forest_area,c("forest_area")) - combined$forest_area<-forest_area - } - - if ("urbanization_WDI" %in% datasources) { - urban <- setNames(readSource("WDI",subtype="SP.URB.TOTL.IN.ZS",convert = FALSE)/100,"urban") - urban<-urban[,sort(getYears(urban)),] - getCells(urban) <- countrycode(getCells(urban),"iso2c","iso3c") - urban <- urban[which(!is.na(dimnames(urban)[[1]])),,] - combined$urban<-urban - } - - if ("population_WDI" %in% datasources) { - - pop <- setNames(readSource("WDI",subtype="SP.POP.TOTL",convert = TRUE),"pop") - pop<-pop[,sort(getYears(pop)),] - pop <- pop[which(!is.na(dimnames(pop)[[1]])),,] - #pop[,"y2014",] <- setYears(pop[,"y2013",])+ setYears(pop[,"y2013",])-setYears(pop[,"y2012",]) - combined$pop<-pop - } - - if ("population_WDI" %in% datasources) { - - pop <- setNames(readSource("WDI",subtype="SP.POP.TOTL",convert = TRUE),"pop") - pop<-pop[,sort(getYears(pop)),] - pop <- pop[which(!is.na(dimnames(pop)[[1]])),,] - #pop[,"y2014",] <- setYears(pop[,"y2013",])+ setYears(pop[,"y2013",])-setYears(pop[,"y2012",]) - combined$pop<-pop - } - - if ("gdp" %in% datasources) { - gdp_pc <- readSource("James",convert = F)[,,"IHME_USD05_PPP_pc"] - gdp_pc <- gdp_pc[,,"IHME_USD05_PPP_pc"] - combined$gdp_pc<-gdp_pc - } - - if ("bodyheight" %in% datasources) { - bodyheight_wrongyears <-readSource("NCDrisc",subtype="height",convert=FALSE) - bodyheight<-new.magpie(cells_and_regions = getRegions(bodyheight_wrongyears), - years = (1961+17):(max(getYears(bodyheight_wrongyears,as.integer = TRUE))+17), - names=getNames(bodyheight_wrongyears)) - for(years in getYears(bodyheight,as.integer = TRUE)){ - bodyheight[,years,]=setYears(bodyheight_wrongyears[,years-17,],years) - } - bodyheight <- setNames(bodyheight,paste0("bodyheight_",getNames(bodyheight))) - combined$bodyheight<-bodyheight - } - - if ("intake_pc_schofield" %in% datasources) { - intake <- calcOutput("Intake2",convert=FALSE, modelinput=TRUE, standardize=FALSE, method="schofield", aggregate=FALSE) - intake <- setNames(collapseNames(intake),"intake_pc_schofield") - combined$intake<-intake - } - - if ("intake_pc_FAO_WHO_UNU1985" %in% datasources) { - intake <- calcOutput("Intake2",convert=FALSE, modelinput=TRUE, standardize=FALSE, method="FAO_WHO_UNU1985", aggregate=FALSE) - intake <- setNames(collapseNames(intake),"intake_pc_FAO_WHO_UNU1985") - combined$intake<-intake - } - - if ("intake_pc_Froehle" %in% datasources) { - intake <- calcOutput("Intake2",convert=FALSE, modelinput=TRUE, standardize=FALSE, method="Froehle", aggregate=FALSE) - intake <- setNames(collapseNames(intake),"intake_pc_Froehle") - combined$intake<-intake - } - - if ("intake_demography" %in% datasources) { - intake <- calcOutput("Intake",convert=FALSE, modelinput=FALSE, standardize=FALSE, method="Froehle", aggregate=FALSE) - intake<-collapseNames(intake[,,"SSP2"][,,c("F","M")]) - getNames(intake)<-paste0("intake_",sub(x = getNames(intake),pattern = "\\.",replacement = "_")) - getSets(intake)<-c("region","year","intake") - combined$intake_demography<-intake - } - - if ("intake_standardized_demography" %in% datasources) { - intake <- calcOutput("Intake",convert=FALSE, modelinput=FALSE, standardize="BMI", method="Froehle", aggregate=FALSE) - intake<-collapseNames(intake[,,"SSP2"][,,c("F","M")]) - getNames(intake)<-paste0("intake_standardized_",sub(x = getNames(intake),pattern = "\\.",replacement = "_")) - getSets(intake)<-c("region","year","intake_standardized") - combined$intake_standardized<-intake - } - - if ("intake_pc_standardized_BMI_FAO_WHO_UNU1985" %in% datasources) { - intake <- calcOutput("Intake",convert=FALSE, modelinput=TRUE, standardize="BMI", method="FAO_WHO_UNU1985", aggregate=FALSE) - intake <- setNames(collapseNames(intake[,,"SSP2"]),"intake_pc_standardized_BMI_FAO_WHO_UNU1985") - intake <- time_interpolate(intake,interpolated_year = paste0("y",1965:2010),integrate_interpolated_years = FALSE) - combined$intake_BMI<-intake - } - - if ("physical_inactivity" %in% datasources) { - inactive1=readSource("WHO",subtype = "physical_inactivity_adults",convert=FALSE) - inactive2=readSource("WHO",subtype = "physical_inactivity_underaged",convert=FALSE) - getNames(inactive1)<-paste0("inactivity_adults_",getNames(inactive1)) - getNames(inactive2)<-paste0("inactivity_underaged_",getNames(inactive2)) - combined$intake_BMI<-mbind(inactive1,inactive2) - } - - if ("batten_last_20yrs" %in% datasources) { - food_supply_crop <- readSource("FAO",subtype="FSCrop",convert = F) - food_supply_live <- readSource("FAO",subtype="FSLive",convert = F) - food_supply <- toolFAOcombine(food_supply_crop,food_supply_live, combine="Item") - relationmatrix <- toolGetMapping("FAOitems.rda", type = "sectoral", where="moinput") - relationmatrix <- relationmatrix[,which(names(relationmatrix)%in%c("FoodBalanceItem","k"))] - relationmatrix <- relationmatrix[-which(duplicated(relationmatrix[,1])==T),] - - vcat(2,"removing strange values for montenegro in 2004, 2005 and luxemburg in 1990:1999") - food_supply["MNE",c("y2004","y2005"),]=0 - food_supply["LUX",1961:1999,]=0 - - food_supply <- collapseNames(food_supply[,,"food_supply_kcal/cap/day"]) - kcal <- toolAggregate(#x = kcal, - x = food_supply, - rel =relationmatrix, - dim = 3.1, - from = "FoodBalanceItem", - to = "k", - partrel=TRUE) - - kcal<-add_columns(kcal,addnm = c("brans","scp")) - kcal[,,c("brans","scp")]<-0 - - kcal <- kcal[,,"remaining",invert=TRUE] - - missing <- dimSums(kcal,dim=3,na.rm=TRUE) # missing values - missing[missing == 0] <- NA - missing[!is.na(missing)]<-1 - kcal[is.na(kcal)] = 0 - kcal = kcal * missing - - batten<-dimSums(kcal[,,c( - "fish","livst_chick","livst_egg", - "livst_milk","livst_pig","livst_rum", - "oils", - "puls_pro","soybean","groundnut" - )],dim=3) - - kcal<-batten[,(1961+19):max(getYears(batten,as.integer = TRUE)),]*NA - for(year_x in (1961+19):max(getYears(food_supply_crop,as.integer = TRUE))){ - kcal[,year_x,] <- dimSums(batten[,(year_x-19):(year_x-5),],dim=2)/15 - } - combined$kcal_last_20yrs<-setNames(collapseNames(kcal),"batten_last_20yrs") - } - - if("BMI_shr" %in% datasources){ - x<-readSource("NCDrisc",subtype="BMI_shr",convert=FALSE) - mapping<-toolMappingFile(type = "sectoral",name = "NCDriscBMIshr2Lutz.csv",readcsv = TRUE) - Lutz<-calcOutput("Demography",education=FALSE,aggregate = FALSE) - Lutz<-collapseNames(time_interpolate(Lutz[getRegions(x),,"SSP2"],interpolated_year = getYears(x),integrate_interpolated_years = FALSE)) - Lutz2<-toolAggregate(Lutz[,,c(mapping$lutz)],rel = mapping,from = "lutz",to = "NCDrisc",dim=3.2) - getSets(Lutz2)<-c("country","year","sex","age") - Lutz2<-dimOrder(Lutz2,perm = c(2,1)) - - mapping<-toolMappingFile(type = "sectoral",name = "NCDriscBMIshr2agegroups.csv",readcsv = TRUE) - twogroups<-toolAggregate(x,rel = mapping,weight = Lutz2,from = "NCDrisc",to="agegroups",dim=3.1) - - dimnames(twogroups)[[3]]<-gsub(pattern = "\\.",replacement = "_",dimnames(twogroups)[[3]]) - - combined$BMI_shr<-twogroups - } - - if("BMI_shr_underaged" %in% datasources){ - x<-readSource("NCDrisc",subtype="BMI_shr_underaged",convert=FALSE) - x<-x[,,c("age5", "age6", "age7", "age8", "age9", "age10", "age11", "age12", "age13", "age14")] - x<-dimSums(x,dim=3.1)/fulldim(x)[[1]][[3]] - dimnames(x)[[3]]<-gsub(pattern = "\\.",replacement = "_",dimnames(x)[[3]]) - getSets(x)<-c("iso","year","group") - combined$BMI_shr_underaged<-x - } - - if ("BMI" %in% datasources){ - - x<-readSource("NCDrisc",subtype="BMI",convert=FALSE) - mapping<-toolMappingFile(type = "sectoral",name = "NCDrisc2Lutz.csv",readcsv = TRUE) - BMI<-new.magpie(cells_and_regions = getRegions(x),years = getYears(x),names = c(paste0(unique(mapping$lutz),".M"),paste0(unique(mapping$lutz),".F"))) - for(i in getNames(BMI,dim=1)){ - item<-mapping$NCDrisc[mapping$lutz==i] - BMI[,,i]=dimSums(x[,,item],dim="age")/length(item) - } - getNames(BMI)<-paste0("BMI_",sub(x = getNames(BMI),pattern = "\\.",replacement = "_")) - getSets(BMI)<-c("region","year","BMI") - combined$BMI<-BMI - } - - if ("kcal" %in% datasources) { - food_supply_crop <- readSource("FAO",subtype="FSCrop",convert = F) - food_supply_live <- readSource("FAO",subtype="FSLive",convert = F) - food_supply <- toolFAOcombine(food_supply_crop,food_supply_live, combine="Item") - relationmatrix <- toolGetMapping("FAOitems.rda", type = "sectoral", where="moinput") - relationmatrix <- relationmatrix[,which(names(relationmatrix)%in%c("FoodBalanceItem","k"))] - relationmatrix <- relationmatrix[-which(duplicated(relationmatrix[,1])==T),] - - vcat(2,"removing strange values for montenegro in 2004, 2005 and luxemburg in 1990:1999") - food_supply["MNE",c("y2004","y2005"),]=0 - food_supply["LUX",1961:1999,]=0 - - food_supply <- collapseNames(food_supply[,,"food_supply_kcal/cap/day"]) - kcal <- toolAggregate(#x = kcal, - x = food_supply, - rel =relationmatrix, - dim = 3.1, - from = "FoodBalanceItem", - to = "k", - partrel=TRUE) - - kcal<-add_columns(kcal,addnm = c("brans","scp")) - kcal[,,c("brans","scp")]<-0 - - kcal <- kcal[,,"remaining",invert=TRUE] - - - missing <- dimSums(kcal,dim=3,na.rm=TRUE) # missing values - missing[missing == 0] <- NA - missing[!is.na(missing)]<-1 - kcal[is.na(kcal)] = 0 - kcal = kcal * missing - combined$kcal<-kcal - } - - if ("demographics" %in% datasources){ - Lutz <- readSource("Lutz2014",convert=FALSE) - LutzSSP2 <- time_interpolate(Lutz[,,"SSP2"], - paste0("y", 1970:2011), - integrate_interpolated_years=F, - extrapolation_type = "linear") - TotalBoth <- LutzSSP2[,,"Total"][,,"Both"][,,"All"] - TotalFem <- LutzSSP2[,,"Total"][,,"Female"][,,"All"] - TotalBothNoKids <- dimSums(LutzSSP2[,,c("Under 15","Total"),invert=TRUE][,,"Both"][,,"All"],dim=3.4) - FemaleNoKids <- dimSums(LutzSSP2[,,c("Under 15","Total"),invert=TRUE][,,"Both"][,,"All"],dim=3.4) - - ### gender ### - femShare <- mbind(setNames( - dimSums(TotalFem/TotalBoth, dim=3), - "femaleShare")) - - ### education ### - education<-mbind( - setNames(dimSums(LutzSSP2[,,"Post Secondary"][,,"Both"][,,"All"] - / TotalBothNoKids, - dim=3), - "college"), - setNames(dimSums(LutzSSP2[,,"Post Secondary"][,,"Female"][,,"All"] - / FemaleNoKids, - dim=3), - "femcollege"), - setNames(dimSums(LutzSSP2[,,c("Incomplete Primary", - "No Education", - "Primary")][,,"Both"][,,"All"] - / TotalBothNoKids, - dim=3), - "low_education") - ) - #education[,,2] <- education[,,2] - education[,,1] - - if(any(education<0, na.rm=TRUE)) - { - stop("education share smaller 0") - } - if(any(education>1, na.rm=TRUE)) - { - stop("education share larger 1") - } - - ### age ### - age<-mbind( - setNames(dimSums(LutzSSP2[,,"Total"][,,"Both"][,,c( - "0--4","5--9","10--14")] - / TotalBoth, - dim=3), - "below15"), - setNames(dimSums(LutzSSP2[,,"Total"][,,"Both"][,,c( - "15--19","20--24","25--29","30--34","35--39", - "40--44","45--49","50--54","55--59","60--64")] - / TotalBoth, - dim=3), - "15-64"), - setNames(dimSums(LutzSSP2[,,"Total"][,,"Both"][,,c( - "65--69","70--74","75--79","80--84", - "85--89","90--94","95--99","100+")] - / TotalBoth, - dim=3), - "above64") - ) - demographics<-mbind(education,age,femShare) - combined$demographics<-demographics - } - - if ("food_price" %in% datasources){ - price <- collapseNames(calcOutput("PriceAgriculture",datasource = "WBGEM",aggregate = FALSE)) - - dimnames(price)[[1]] <- "DEU" - price <- toolCountryFill(price,fill = 0 ) - for(i in getRegions(price)){ - price[i,,] <- as.matrix(price["DEU",,]) - } - getNames(price) <- paste("price",getNames(price),sep="_") - combined$food_price <- price - } - - if ("climate"%in% datasources) { - CZ <- readSource("Koeppen",convert=FALSE) #klimazone - CZ <- dimSums(CZ[,,c("kg_p_af","kg_p_aw","kg_p_bs","kg_p_cf","kg_p_df","kg_p_e")],dim=3) - CZ <- setNames(CZ,"climate") - CZ <- add_columns(setYears(CZ,"y2010"), setdiff(getYears(combined[[1]]),"y2010"),dim = 2.1) - CZ[,,]<-setYears(CZ[,"y2010",],NULL) - getYears(combined[[1]]) - combined$climate<-CZ - } - - - mbindCommonDimensions <- function(magpielist){ - if(!is.list(magpielist)){magpielist<-list(magpielist)} - if (length(magpielist)==2){ - a<-magpielist[[1]] - b<-magpielist[[2]] - ab<-c(getRegions(a),getRegions(b)) - ab_regions <- ab[duplicated(ab)] - - ab<-c(getYears(a),getYears(b)) - ab_time <- ab[duplicated(ab)] - - ab<-list(mbind(a[ab_regions,ab_time,],b[ab_regions,ab_time,])) - mbindCommonDimensions(ab) - } else if (length(magpielist)>2) { - ab<-mbindCommonDimensions(list(magpielist[[1]],magpielist[[2]])) - ab<-append(list(ab),magpielist[3:length(magpielist)]) - mbindCommonDimensions(ab) - } else if (length(magpielist)==0) { - stop("empty list") - } else {return(magpielist[[1]])} - } - - out<-mbindCommonDimensions(combined) - - ### aggregation weights - - - pop <- setNames(readSource("WDI",subtype="SP.POP.TOTL",convert = T),"weight") - #pop[,"y2014",] <- setYears(pop[,"y2013",])+ setYears(pop[,"y2013",])-setYears(pop[,"y2012",]) - - out<-mbindCommonDimensions(list(out,pop)) - weight<-x<-out - weight[,,]<-setNames(out[,,"weight"],NULL) - if("pop"%in%getNames(weight)){ weight[,,"pop"]<-0 } - - - return(list(x = x, - weight = weight, - unit = "share of population, per-capita income or per-capita consumption", - description = "Merged dataset containing raw data for regression", - min = 0, - na_warning=FALSE, - isocountries = FALSE) - ) -} +#' @title calcCollectRegressionData +#' @description collects regression data using un-converted raw data sources, and crops the data that only joint years and countries are selected. +#' +#' @param datasources All datasources that shall be returned. Due to the cropping of data which is not present in all datasources, reducing the number of datasources will increase the number of observations. +#' @return List of magpie objects with results on country level, weight on country level, unit and description. +#' @author Benjamin Leon Bodirsky, Eleonora Martinelli, Abhijeet Mishra, Xiaoxi Wang +#' @examples +#' +#' \dontrun{ +#' calcOutput("CollectRegressionData",aggregate=F) +#' } +#' + +#' @importFrom countrycode countrycode +#' @importFrom magpiesets findset +#' @importFrom moinput toolFAOcombine +#' @importFrom stats quantile +#' @import magclass +#' @import madrat +#' @export + +calcCollectRegressionData <- function(datasources) + { + combined<-list() + + if ("wooddemand" %in% datasources) { + wooddemand <- calcOutput("FAOForestryDemand",aggregate = FALSE) + roundwood <- wooddemand[,,"roundwood.domestic_supply"] + roundwood <- setNames(roundwood,c("roundwood")) + + wood <- wooddemand[,,"wood.domestic_supply"] + wood <- setNames(wood,c("wood")) + + woodfuel <- wooddemand[,,"woodfuel.domestic_supply"] + woodfuel <- setNames(woodfuel,c("woodfuel")) + + wooddemand <- mbind(roundwood,wood,woodfuel) + wooddemand <- wooddemand[,sort(getYears(wooddemand)),] + wooddemand <- wooddemand[which(!is.na(dimnames(wooddemand)[[1]])),,] + wooddemand[c("TWN","AIA","NRU","VGB","KWT","COK"),,] <- 0 + + wooddemand[,,"woodfuel"] <- wooddemand[,,"woodfuel"]*1000/632.5 ## mio.m3 + wooddemand[,,"wood"] <- wooddemand[,,"wood"]*1000/307.1 ## mio.m3 + combined$wooddemand<-wooddemand + } + + if ("SelfSuff" %in% datasources) { + SelfSuff_w <- calcOutput("TradeSelfSuff",convert = F)[,,"wood"] + SelfSuff_wf <- calcOutput("TradeSelfSuff",convert = F)[,,"woodfuel"] + SelfSuff <- mbind(SelfSuff_w,SelfSuff_wf) + SelfSuff <- SelfSuff[,sort(getYears(SelfSuff)),] + SelfSuff <- SelfSuff[which(!is.na(dimnames(SelfSuff)[[1]])),,] + getNames(SelfSuff) <- paste0("ss_",getNames(SelfSuff)) + combined$SelfSuff<-SelfSuff + } + + if ("timber_demand" %in% datasources) { + timber_demand <- collapseNames(calcOutput("TimberDemand",aggregate = FALSE)[,,"domestic_supply"]) + combined$forestry<-timber_demand + } + + if ("forest_area" %in% datasources) { + FA_LUI <- calcOutput("LanduseInitialisation",aggregate = FALSE) + + forest_area <- dimSums(FA_LUI[,,c("forestry","primforest","secdforest")],dim=3) + forest_area <- setNames(forest_area,c("forest_area")) + combined$forest_area<-forest_area + } + + if ("urbanization_WDI" %in% datasources) { + urban <- setNames(readSource("WDI",subtype="SP.URB.TOTL.IN.ZS",convert = FALSE)/100,"urban") + urban<-urban[,sort(getYears(urban)),] + getCells(urban) <- countrycode(getCells(urban),"iso2c","iso3c") + urban <- urban[which(!is.na(dimnames(urban)[[1]])),,] + combined$urban<-urban + } + + if ("population_WDI" %in% datasources) { + + pop <- setNames(readSource("WDI",subtype="SP.POP.TOTL",convert = TRUE),"pop") + pop<-pop[,sort(getYears(pop)),] + pop <- pop[which(!is.na(dimnames(pop)[[1]])),,] + #pop[,"y2014",] <- setYears(pop[,"y2013",])+ setYears(pop[,"y2013",])-setYears(pop[,"y2012",]) + combined$pop<-pop + } + + if ("population_WDI" %in% datasources) { + + pop <- setNames(readSource("WDI",subtype="SP.POP.TOTL",convert = TRUE),"pop") + pop<-pop[,sort(getYears(pop)),] + pop <- pop[which(!is.na(dimnames(pop)[[1]])),,] + #pop[,"y2014",] <- setYears(pop[,"y2013",])+ setYears(pop[,"y2013",])-setYears(pop[,"y2012",]) + combined$pop<-pop + } + + if ("gdp" %in% datasources) { + gdp_pc <- readSource("James",convert = F)[,,"IHME_USD05_PPP_pc"] + gdp_pc <- gdp_pc[,,"IHME_USD05_PPP_pc"] + combined$gdp_pc<-gdp_pc + } + + if ("bodyheight" %in% datasources) { + bodyheight_wrongyears <-readSource("NCDrisc",subtype="height",convert=FALSE) + bodyheight<-new.magpie(cells_and_regions = getRegions(bodyheight_wrongyears), + years = (1961+17):(max(getYears(bodyheight_wrongyears,as.integer = TRUE))+17), + names=getNames(bodyheight_wrongyears)) + for(years in getYears(bodyheight,as.integer = TRUE)){ + bodyheight[,years,]=setYears(bodyheight_wrongyears[,years-17,],years) + } + bodyheight <- setNames(bodyheight,paste0("bodyheight_",getNames(bodyheight))) + combined$bodyheight<-bodyheight + } + + if ("intake_pc_schofield" %in% datasources) { + intake <- calcOutput("Intake2",convert=FALSE, modelinput=TRUE, standardize=FALSE, method="schofield", aggregate=FALSE) + intake <- setNames(collapseNames(intake),"intake_pc_schofield") + combined$intake<-intake + } + + if ("intake_pc_FAO_WHO_UNU1985" %in% datasources) { + intake <- calcOutput("Intake2",convert=FALSE, modelinput=TRUE, standardize=FALSE, method="FAO_WHO_UNU1985", aggregate=FALSE) + intake <- setNames(collapseNames(intake),"intake_pc_FAO_WHO_UNU1985") + combined$intake<-intake + } + + if ("intake_pc_Froehle" %in% datasources) { + intake <- calcOutput("Intake2",convert=FALSE, modelinput=TRUE, standardize=FALSE, method="Froehle", aggregate=FALSE) + intake <- setNames(collapseNames(intake),"intake_pc_Froehle") + combined$intake<-intake + } + + if ("intake_demography" %in% datasources) { + intake <- calcOutput("Intake",convert=FALSE, modelinput=FALSE, standardize=FALSE, method="Froehle", aggregate=FALSE) + intake<-collapseNames(intake[,,"SSP2"][,,c("F","M")]) + getNames(intake)<-paste0("intake_",sub(x = getNames(intake),pattern = "\\.",replacement = "_")) + getSets(intake)<-c("region","year","intake") + combined$intake_demography<-intake + } + + if ("intake_standardized_demography" %in% datasources) { + intake <- calcOutput("Intake",convert=FALSE, modelinput=FALSE, standardize="BMI", method="Froehle", aggregate=FALSE) + intake<-collapseNames(intake[,,"SSP2"][,,c("F","M")]) + getNames(intake)<-paste0("intake_standardized_",sub(x = getNames(intake),pattern = "\\.",replacement = "_")) + getSets(intake)<-c("region","year","intake_standardized") + combined$intake_standardized<-intake + } + + if ("intake_pc_standardized_BMI_FAO_WHO_UNU1985" %in% datasources) { + intake <- calcOutput("Intake",convert=FALSE, modelinput=TRUE, standardize="BMI", method="FAO_WHO_UNU1985", aggregate=FALSE) + intake <- setNames(collapseNames(intake[,,"SSP2"]),"intake_pc_standardized_BMI_FAO_WHO_UNU1985") + intake <- time_interpolate(intake,interpolated_year = paste0("y",1965:2010),integrate_interpolated_years = FALSE) + combined$intake_BMI<-intake + } + + if ("physical_inactivity" %in% datasources) { + inactive1=readSource("WHO",subtype = "physical_inactivity_adults",convert=FALSE) + inactive2=readSource("WHO",subtype = "physical_inactivity_underaged",convert=FALSE) + getNames(inactive1)<-paste0("inactivity_adults_",getNames(inactive1)) + getNames(inactive2)<-paste0("inactivity_underaged_",getNames(inactive2)) + combined$intake_BMI<-mbind(inactive1,inactive2) + } + + if ("batten_last_20yrs" %in% datasources) { + food_supply_crop <- readSource("FAO",subtype="FSCrop",convert = F) + food_supply_live <- readSource("FAO",subtype="FSLive",convert = F) + food_supply <- toolFAOcombine(food_supply_crop,food_supply_live, combine="Item") + relationmatrix <- toolGetMapping("FAOitems.rda", type = "sectoral", where="moinput") + relationmatrix <- relationmatrix[,which(names(relationmatrix)%in%c("FoodBalanceItem","k"))] + relationmatrix <- relationmatrix[-which(duplicated(relationmatrix[,1])==T),] + + vcat(2,"removing strange values for montenegro in 2004, 2005 and luxemburg in 1990:1999") + food_supply["MNE",c("y2004","y2005"),]=0 + food_supply["LUX",1961:1999,]=0 + + food_supply <- collapseNames(food_supply[,,"food_supply_kcal/cap/day"]) + kcal <- toolAggregate(#x = kcal, + x = food_supply, + rel =relationmatrix, + dim = 3.1, + from = "FoodBalanceItem", + to = "k", + partrel=TRUE) + + kcal<-add_columns(kcal,addnm = c("brans","scp")) + kcal[,,c("brans","scp")]<-0 + + kcal <- kcal[,,"remaining",invert=TRUE] + + missing <- dimSums(kcal,dim=3,na.rm=TRUE) # missing values + missing[missing == 0] <- NA + missing[!is.na(missing)]<-1 + kcal[is.na(kcal)] = 0 + kcal = kcal * missing + + batten<-dimSums(kcal[,,c( + "fish","livst_chick","livst_egg", + "livst_milk","livst_pig","livst_rum", + "oils", + "puls_pro","soybean","groundnut" + )],dim=3) + + kcal<-batten[,(1961+19):max(getYears(batten,as.integer = TRUE)),]*NA + for(year_x in (1961+19):max(getYears(food_supply_crop,as.integer = TRUE))){ + kcal[,year_x,] <- dimSums(batten[,(year_x-19):(year_x-5),],dim=2)/15 + } + combined$kcal_last_20yrs<-setNames(collapseNames(kcal),"batten_last_20yrs") + } + + if("BMI_shr" %in% datasources){ + x<-readSource("NCDrisc",subtype="BMI_shr",convert=FALSE) + mapping<-toolMappingFile(type = "sectoral",name = "NCDriscBMIshr2Lutz.csv",readcsv = TRUE) + Lutz<-calcOutput("Demography",education=FALSE,aggregate = FALSE) + Lutz<-collapseNames(time_interpolate(Lutz[getRegions(x),,"SSP2"],interpolated_year = getYears(x),integrate_interpolated_years = FALSE)) + Lutz2<-toolAggregate(Lutz[,,c(mapping$lutz)],rel = mapping,from = "lutz",to = "NCDrisc",dim=3.2) + getSets(Lutz2)<-c("country","year","sex","age") + Lutz2<-dimOrder(Lutz2,perm = c(2,1)) + + mapping<-toolMappingFile(type = "sectoral",name = "NCDriscBMIshr2agegroups.csv",readcsv = TRUE) + twogroups<-toolAggregate(x,rel = mapping,weight = Lutz2,from = "NCDrisc",to="agegroups",dim=3.1) + + dimnames(twogroups)[[3]]<-gsub(pattern = "\\.",replacement = "_",dimnames(twogroups)[[3]]) + + combined$BMI_shr<-twogroups + } + + if("BMI_shr_underaged" %in% datasources){ + x<-readSource("NCDrisc",subtype="BMI_shr_underaged",convert=FALSE) + x<-x[,,c("age5", "age6", "age7", "age8", "age9", "age10", "age11", "age12", "age13", "age14")] + x<-dimSums(x,dim=3.1)/fulldim(x)[[1]][[3]] + dimnames(x)[[3]]<-gsub(pattern = "\\.",replacement = "_",dimnames(x)[[3]]) + getSets(x)<-c("iso","year","group") + combined$BMI_shr_underaged<-x + } + + if ("BMI" %in% datasources){ + + x<-readSource("NCDrisc",subtype="BMI",convert=FALSE) + mapping<-toolMappingFile(type = "sectoral",name = "NCDrisc2Lutz.csv",readcsv = TRUE) + BMI<-new.magpie(cells_and_regions = getRegions(x),years = getYears(x),names = c(paste0(unique(mapping$lutz),".M"),paste0(unique(mapping$lutz),".F"))) + for(i in getNames(BMI,dim=1)){ + item<-mapping$NCDrisc[mapping$lutz==i] + BMI[,,i]=dimSums(x[,,item],dim="age")/length(item) + } + getNames(BMI)<-paste0("BMI_",sub(x = getNames(BMI),pattern = "\\.",replacement = "_")) + getSets(BMI)<-c("region","year","BMI") + combined$BMI<-BMI + } + + if ("kcal" %in% datasources) { + food_supply_crop <- readSource("FAO",subtype="FSCrop",convert = F) + food_supply_live <- readSource("FAO",subtype="FSLive",convert = F) + food_supply <- toolFAOcombine(food_supply_crop,food_supply_live, combine="Item") + relationmatrix <- toolGetMapping("FAOitems.rda", type = "sectoral", where="moinput") + relationmatrix <- relationmatrix[,which(names(relationmatrix)%in%c("FoodBalanceItem","k"))] + relationmatrix <- relationmatrix[-which(duplicated(relationmatrix[,1])==T),] + + vcat(2,"removing strange values for montenegro in 2004, 2005 and luxemburg in 1990:1999") + food_supply["MNE",c("y2004","y2005"),]=0 + food_supply["LUX",1961:1999,]=0 + + food_supply <- collapseNames(food_supply[,,"food_supply_kcal/cap/day"]) + kcal <- toolAggregate(#x = kcal, + x = food_supply, + rel =relationmatrix, + dim = 3.1, + from = "FoodBalanceItem", + to = "k", + partrel=TRUE) + + kcal<-add_columns(kcal,addnm = c("brans","scp")) + kcal[,,c("brans","scp")]<-0 + + kcal <- kcal[,,"remaining",invert=TRUE] + + + missing <- dimSums(kcal,dim=3,na.rm=TRUE) # missing values + missing[missing == 0] <- NA + missing[!is.na(missing)]<-1 + kcal[is.na(kcal)] = 0 + kcal = kcal * missing + combined$kcal<-kcal + } + + if ("demographics" %in% datasources){ + Lutz <- readSource("Lutz2014",convert=FALSE) + LutzSSP2 <- time_interpolate(Lutz[,,"SSP2"], + paste0("y", 1970:2011), + integrate_interpolated_years=F, + extrapolation_type = "linear") + TotalBoth <- LutzSSP2[,,"Total"][,,"Both"][,,"All"] + TotalFem <- LutzSSP2[,,"Total"][,,"Female"][,,"All"] + TotalBothNoKids <- dimSums(LutzSSP2[,,c("Under 15","Total"),invert=TRUE][,,"Both"][,,"All"],dim=3.4) + FemaleNoKids <- dimSums(LutzSSP2[,,c("Under 15","Total"),invert=TRUE][,,"Both"][,,"All"],dim=3.4) + + ### gender ### + femShare <- mbind(setNames( + dimSums(TotalFem/TotalBoth, dim=3), + "femaleShare")) + + ### education ### + education<-mbind( + setNames(dimSums(LutzSSP2[,,"Post Secondary"][,,"Both"][,,"All"] + / TotalBothNoKids, + dim=3), + "college"), + setNames(dimSums(LutzSSP2[,,"Post Secondary"][,,"Female"][,,"All"] + / FemaleNoKids, + dim=3), + "femcollege"), + setNames(dimSums(LutzSSP2[,,c("Incomplete Primary", + "No Education", + "Primary")][,,"Both"][,,"All"] + / TotalBothNoKids, + dim=3), + "low_education") + ) + #education[,,2] <- education[,,2] - education[,,1] + + if(any(education<0, na.rm=TRUE)) + { + stop("education share smaller 0") + } + if(any(education>1, na.rm=TRUE)) + { + stop("education share larger 1") + } + + ### age ### + age<-mbind( + setNames(dimSums(LutzSSP2[,,"Total"][,,"Both"][,,c( + "0--4","5--9","10--14")] + / TotalBoth, + dim=3), + "below15"), + setNames(dimSums(LutzSSP2[,,"Total"][,,"Both"][,,c( + "15--19","20--24","25--29","30--34","35--39", + "40--44","45--49","50--54","55--59","60--64")] + / TotalBoth, + dim=3), + "15-64"), + setNames(dimSums(LutzSSP2[,,"Total"][,,"Both"][,,c( + "65--69","70--74","75--79","80--84", + "85--89","90--94","95--99","100+")] + / TotalBoth, + dim=3), + "above64") + ) + demographics<-mbind(education,age,femShare) + combined$demographics<-demographics + } + + if ("food_price" %in% datasources){ + price <- collapseNames(calcOutput("PriceAgriculture",datasource = "WBGEM",aggregate = FALSE)) + + dimnames(price)[[1]] <- "DEU" + price <- toolCountryFill(price,fill = 0 ) + for(i in getRegions(price)){ + price[i,,] <- as.matrix(price["DEU",,]) + } + getNames(price) <- paste("price",getNames(price),sep="_") + combined$food_price <- price + } + + if ("climate"%in% datasources) { + CZ <- readSource("Koeppen",convert=FALSE) #klimazone + CZ <- dimSums(CZ[,,c("kg_p_af","kg_p_aw","kg_p_bs","kg_p_cf","kg_p_df","kg_p_e")],dim=3) + CZ <- setNames(CZ,"climate") + CZ <- add_columns(setYears(CZ,"y2010"), setdiff(getYears(combined[[1]]),"y2010"),dim = 2.1) + CZ[,,]<-setYears(CZ[,"y2010",],NULL) + getYears(combined[[1]]) + combined$climate<-CZ + } + + + mbindCommonDimensions <- function(magpielist){ + if(!is.list(magpielist)){magpielist<-list(magpielist)} + if (length(magpielist)==2){ + a<-magpielist[[1]] + b<-magpielist[[2]] + ab<-c(getRegions(a),getRegions(b)) + ab_regions <- ab[duplicated(ab)] + + ab<-c(getYears(a),getYears(b)) + ab_time <- ab[duplicated(ab)] + + ab<-list(mbind(a[ab_regions,ab_time,],b[ab_regions,ab_time,])) + mbindCommonDimensions(ab) + } else if (length(magpielist)>2) { + ab<-mbindCommonDimensions(list(magpielist[[1]],magpielist[[2]])) + ab<-append(list(ab),magpielist[3:length(magpielist)]) + mbindCommonDimensions(ab) + } else if (length(magpielist)==0) { + stop("empty list") + } else {return(magpielist[[1]])} + } + + out<-mbindCommonDimensions(combined) + + ### aggregation weights + + + pop <- setNames(readSource("WDI",subtype="SP.POP.TOTL",convert = T),"weight") + #pop[,"y2014",] <- setYears(pop[,"y2013",])+ setYears(pop[,"y2013",])-setYears(pop[,"y2012",]) + + out<-mbindCommonDimensions(list(out,pop)) + weight<-x<-out + weight[,,]<-setNames(out[,,"weight"],NULL) + if("pop"%in%getNames(weight)){ weight[,,"pop"]<-0 } + + + return(list(x = x, + weight = weight, + unit = "share of population, per-capita income or per-capita consumption", + description = "Merged dataset containing raw data for regression", + min = 0, + na_warning=FALSE, + isocountries = FALSE) + ) +} diff --git a/R/mrrgression-package.R b/R/mrrgression-package.R index feb4bb2..f4f78ee 100644 --- a/R/mrrgression-package.R +++ b/R/mrrgression-package.R @@ -1,18 +1,18 @@ -#' Moinput Regression function library -#' -#' Package contains functions to estimate model parameters -#' -#' \tabular{ll}{ Package: \tab mrregression\cr Type: \tab Package\cr Version: \tab -#' 0.1\cr Date: \tab 2016-09-23\cr License: \tab LGPL-3\cr LazyLoad: \tab -#' yes\cr } -#' -#' @name mrregression-package -#' @aliases mrregression-package mrregression -#' @docType package -#' @author Benjamin Leon Bodirsky, Antonia Walther -#' -#' Maintainer: Benjamin Leon Bodirsky -NULL - - - +#' Moinput Regression function library +#' +#' Package contains functions to estimate model parameters +#' +#' \tabular{ll}{ Package: \tab mrregression\cr Type: \tab Package\cr Version: \tab +#' 0.1\cr Date: \tab 2016-09-23\cr License: \tab LGPL-3\cr LazyLoad: \tab +#' yes\cr } +#' +#' @name mrregression-package +#' @aliases mrregression-package mrregression +#' @docType package +#' @author Benjamin Leon Bodirsky, Antonia Walther +#' +#' Maintainer: Benjamin Leon Bodirsky +NULL + + + diff --git a/R/nlsAddLines.R b/R/nlsAddLines.R index d0a7666..52c206a 100644 --- a/R/nlsAddLines.R +++ b/R/nlsAddLines.R @@ -1,54 +1,54 @@ -#' @title nlsAddLines -#' @description Adds lines of specific countries into the plot of the function nlsregression. -#' nlsregression has to be based on magpie objects for x,y,weight -#' -#' @param x magpie object with x values -#' @param y magpie object with y values -#' @param weight magpie object with weight -#' @param x_log10 same as in nlsregression -#' @param colors colors of the lines -#' @param countries Choice of countries -#' @param labels If TRUE, the region, staryear and endyear will be plotted to each line. -#' @seealso -#' \code{\link{nlsregression}} -#' -#' @return vector with ISO-countrycodes -#' @author Benjamin Leon Bodirsky -#' @export -#' @examples -#' -#' \dontrun{ -#' data(population_magpie) -#' nlsregression(y=population_magpie[,,1],x=population_magpie[,,2], -#' weight = population_magpie[,,1],func = y~a*x+b) -#' nlsAddLines(y=population_magpie[,,1],x=population_magpie[,,2], -#' weight = population_magpie[,,1],countries=1:3,colors=1:3) -#' } -#' @importFrom graphics lines text -#' -#' -nlsAddLines<-function(y,x,countries=1:5,weight=NULL,x_log10=FALSE,colors="black",labels=TRUE){ - if(x_log10==TRUE){ - plot_x_function=log10 - } else { - plot_x_function=function(x){x} - } - if (all(is.numeric(countries))){ - if (is.null(weight)){"If no specific countries are selected, weight has to be provided"} - countries<-getRegions(sort(dimSums(weight,dim=c(2,3)),decreasing = T)[countries]) - } - if (length(colors)==1){ - colors=rep(x = colors,length(countries)) - } - for (i in length(countries):1) { - country<-countries[i] - lines(y[country,,] ~ plot_x_function(x[country,,]),lwd = 2,col=colors[i]) - if(labels==TRUE){ - maxyear=getYears(x)[length(getYears(x))] - text(x = plot_x_function(as.vector(x[country,,])[1]),y = as.vector(y[country,,])[1],labels = paste(country,getYears(x[,1,])),col=colors[i],cex=1) - text(x = plot_x_function(as.vector(x[country,maxyear,])),y = as.vector(y[country,maxyear,]),labels = paste(country,maxyear),col=colors[i],cex=1) - } - } -} - - +#' @title nlsAddLines +#' @description Adds lines of specific countries into the plot of the function nlsregression. +#' nlsregression has to be based on magpie objects for x,y,weight +#' +#' @param x magpie object with x values +#' @param y magpie object with y values +#' @param weight magpie object with weight +#' @param x_log10 same as in nlsregression +#' @param colors colors of the lines +#' @param countries Choice of countries +#' @param labels If TRUE, the region, staryear and endyear will be plotted to each line. +#' @seealso +#' \code{\link{nlsregression}} +#' +#' @return vector with ISO-countrycodes +#' @author Benjamin Leon Bodirsky +#' @export +#' @examples +#' +#' \dontrun{ +#' data(population_magpie) +#' nlsregression(y=population_magpie[,,1],x=population_magpie[,,2], +#' weight = population_magpie[,,1],func = y~a*x+b) +#' nlsAddLines(y=population_magpie[,,1],x=population_magpie[,,2], +#' weight = population_magpie[,,1],countries=1:3,colors=1:3) +#' } +#' @importFrom graphics lines text +#' +#' +nlsAddLines<-function(y,x,countries=1:5,weight=NULL,x_log10=FALSE,colors="black",labels=TRUE){ + if(x_log10==TRUE){ + plot_x_function=log10 + } else { + plot_x_function=function(x){x} + } + if (all(is.numeric(countries))){ + if (is.null(weight)){"If no specific countries are selected, weight has to be provided"} + countries<-getRegions(sort(dimSums(weight,dim=c(2,3)),decreasing = T)[countries]) + } + if (length(colors)==1){ + colors=rep(x = colors,length(countries)) + } + for (i in length(countries):1) { + country<-countries[i] + lines(y[country,,] ~ plot_x_function(x[country,,]),lwd = 2,col=colors[i]) + if(labels==TRUE){ + maxyear=getYears(x)[length(getYears(x))] + text(x = plot_x_function(as.vector(x[country,,])[1]),y = as.vector(y[country,,])[1],labels = paste(country,getYears(x[,1,])),col=colors[i],cex=1) + text(x = plot_x_function(as.vector(x[country,maxyear,])),y = as.vector(y[country,maxyear,]),labels = paste(country,maxyear),col=colors[i],cex=1) + } + } +} + + diff --git a/R/nlsregression.R b/R/nlsregression.R index 9742614..e025524 100644 --- a/R/nlsregression.R +++ b/R/nlsregression.R @@ -1,499 +1,499 @@ -#' @title nlsregression -#' -#' @description Creates regression parameter estimates and plots with any function you want -#' that has no more than two independent variables -#' -#' -#' @param func function that shall be fitted. Function should contain the -#' dependent variable y and and the independent variable x, eventually a second -#' independent variable z. All other unknowns are treated as parameters that -#' are estimated. -#' @param y dependent variable,vector -#' @param x independent variable,vector -#' @param z optional independent variable,vector -#' @param startvalues the optimization algorithm may require starting values -#' for the fitting procedure. provide them in a list with the parameter names: -#' e.g. list(a=3,b=2) -#' @param weight optional weight,vector -#' @param weighting if weighting is TRUE, the fit will minimize the weighted residuals -#' @param xlab name of x axis in plot -#' @param ylab name of y axis in plot -#' @param header plot function main argument -#' @param z_plot_lines vector>1 of values for z you want to be plotted into the -#' graph -#' @param weightcolorpoints if TRUE, the points are clustered into three -#' quantiles according to their weight and coloured lighter for low weights. -#' @param x_log10 allows log10 scale for X axis if set to TRUE. Only changes the picture, not -#' the regression! -#' @param plot_x_function depreciated, please do not enter into function call. -#' @param toPlot "all", "frame" (axis etc), "observations" (points), "regressionline" (line), "infos" (parameters, R2) -#' @param regressioncolor color of regression line and paramter text -#' @param weight_threshold if numeric, all countries below this threshold will be excluded (e.g. to exclude minor islands) -#' @param ... will be passed on to function nls -#' @return A nice picture and regression parameters or eventually some errors. -#' @author Benjamin Leon Bodirsky, Susanne Rolinski, Xiaoxi Wang -#' @examples -#' \dontrun{ -#' x=1:10 -#' y=(1:10)^2+1 -#' z=c(10:1) -#' -#' # one independent variable -#' nlsregression(func=y~a*x+b,y=y,x=x,startvalues=list(a=1,b=1)) -#' # two independent variables -#' nlsregression(func=y~a*x^1.1+b*z+c*x,y=y,x=x,z=z,startvalues=list(a=1,b=1,c=0)) -#' # no fit because residuals are zero (excluded from the nls makers due -#' to statistical reasons) -#' nlsregression(func=y~x^a+b,y=y,x=x,z=z,startvalues=list(a=1,b=1,c=0)) -#' -#' DNase1 <- subset(DNase, Run == 1) -#' DNase1$sets<- c(rep(1,8),rep(2,8)) -#' nlsregression(func=y~a*x+b,y=DNase1$density,x=DNase1$conc,startvalues=list(a=1,b=1)) -#' nlsregression(func=y~a*x+b*z,y=DNase1$density,x=DNase1$conc,z=DNase1$sets, -#' startvalues=list(a=0.1344,b=0.2597)) -#' nlsregression(func=y~a*x+b*z,y=DNase1$density,x=DNase1$conc,z=DNase1$sets, -#' startvalues=list(a=0.1344,b=0.2597),plot_x_function=log) -#' } -#' @export -#' @importFrom stats shapiro.test -#' @importFrom stats cor -#' @importFrom stats lm -#' @importFrom stats logLik -#' @importFrom stats nls -#' @importFrom stats predict -#' @importFrom stats resid -#' @importFrom stats var -#' @importFrom stats weighted.mean -#' @importFrom stats weights -#' @importFrom graphics plot abline legend lines points text curve -#' @importFrom grDevices colorRampPalette -#' @importFrom lmtest bptest -#' @importFrom boot corr -#' @importFrom nlstools confint2 - -nlsregression <- function(func, # y ~ a*x/b+x - y, x, z=NULL, - startvalues=NULL, - weight=NULL, - weighting=TRUE, - xlab=NULL, - ylab="y", - header=NULL, - z_plot_lines=NULL, - weightcolorpoints=TRUE, - x_log10=FALSE, - toPlot="all", - plot_x_function="ignore", - regressioncolor="blue", - weight_threshold=NULL, - ...) -{ - rounding_helper<-function(x) { - if ((x>1000)|(x< -1000)) { - x=format(signif(x,4), scientific=TRUE) - } else if ((x<0.01)&(x> -0.01)){ - x=format(signif(x,4), scientific=TRUE) - } else if(x>0){ - x<-format(signif(x,4), scientific=FALSE) - } - return(x) - } - - nlsplotlines<-function(function2,regressioncolor,z_plot_lines,x_log10){ - - if(x_log10==TRUE){ - revert=function(x){10^x} - }else { - revert=function(x){x} - } - if(is.null(z_plot_lines)) { - curve(function2(revert(x)),add = T,col=regressioncolor,lty=1,lwd=3) - } else { - for (i in 1:length(z_plot_lines)) { - curve(function2(revert(x),z=z_plot_lines[i]),add = T,col=regressioncolor[i],lty=1,lwd=3) - } - } - - - - } - - nlsplotinfos<-function(combined, z_plot_lines, plot_x_function, regressioncolor, returnvalue, toPlot){ - - if("infos1"%in%toPlot) { ### if several functions shall be plotted into the same plot - spacecorrection=0.05 - } else if ("infos2"%in%toPlot){ - spacecorrection=0.1 - } else if ("infos3"%in%toPlot){ - spacecorrection=0.15 - } else { - spacecorrection=0 - } - - if(!is.null(z_plot_lines)){ - text(labels = paste0("z:"), - col=regressioncolor, - x=min(plot_x_function(combined$x),na.rm=T), - y=max(combined$y,na.rm=T)*(0.9), - pos=4) - - for (i in 1:length(z_plot_lines)) { - text(labels = paste0(z_plot_lines[i]), - col=regressioncolor[i], - x=min(plot_x_function(combined$x),na.rm=T)+ - max(plot_x_function(combined$x),na.rm=T)*0.05, - y=max(combined$y,na.rm=T)*(0.95-(i*0.05)),pos=4) - } - } - - ###bottomright - text(labels = returnvalue$formula, - col=regressioncolor, - x=max(plot_x_function(combined$x),na.rm=T), - y=min(combined$y,na.rm=T)+ max(combined$y,na.rm=T)*spacecorrection, - pos=2) - - ### topleft - text(labels = paste0("Efron's weighted adj. R2: ", - round(returnvalue$efrons_weighted_adj_r2,2)), - col=regressioncolor, - x=min(plot_x_function(combined$x),na.rm=T), - y=max(combined$y*(1-spacecorrection),na.rm=T), - pos=4) - - ## topright - text(labels = paste0("S: ",rounding_helper(returnvalue$standarderror)), - col=regressioncolor, - x=max(plot_x_function(combined$x),na.rm=T), - y=max(combined$y*(1-spacecorrection),na.rm=T), - pos=2) - - #bottomleft - text(labels = paste0(returnvalue$observations," observations"), - col=regressioncolor, - x=min(plot_x_function(combined$x),na.rm=T), - y=min(combined$y,na.rm=T)+ max(combined$y,na.rm=T)*spacecorrection, - pos=4) - } - - nlsplotframe <- function(combined, xlab, ylab, plot_x_function, header){ - if(is.null(xlab)) { - if(is.primitive(plot_x_function)) { - #xlab=paste0(as.character(substitute(plot_x_function)),"(",xlab,")") - xlab=gsub(".Primitive(\"", "", format(plot_x_function), fixed = TRUE) - xlab=gsub("\")", "", xlab) - xlab<-paste0(xlab,"(x)") - } else { - xlab=gsub(" ", "", format(plot_x_function)[[3]], fixed = TRUE) - } - } - plot(combined$y~plot_x_function(combined$x),type="n", - xlab=xlab,ylab=ylab, - main=header) - } - - nlsplotpoints<-function(combined, plot_x_function, z_plot_lines, colors_f){ - - weight = combined$weight - - weight_classes<-list() - if(!all(weight==1)&(weightcolorpoints==TRUE)) { - weight_classes[[1]]<-quantile(weight,na.rm=T,probs=c(0,0.333)) - weight_classes[[2]]<-quantile(weight,na.rm=T,probs=c(0.333,0.666)) - weight_classes[[3]]<-quantile(weight,na.rm=T,probs=c(0.666,1)) - color_order=c(3,2,1) - } else { - weight_classes[[1]]<-quantile(weight,na.rm=T,probs=c(0,1)) - color_order=c(1) - } - - if(!("z"%in%names(combined))) { - colors_points=c("#000000","#595959","#ADADAD") - for (weight_class_x in (1:length(weight_classes))) { - weight_class_x_elements<-(weight>=weight_classes[[weight_class_x]][1])&(weight<=weight_classes[[weight_class_x]][2]) - tmp<-which(weight_class_x_elements) - points(combined$y[tmp]~plot_x_function(combined$x[tmp]),pch=1,cex=0.5,col=colors_points[color_order[weight_class_x]]) - } - }else { - - for (weight_class_x in (1:length(weight_classes))) { - weight_class_x_elements<-(weight>=weight_classes[[weight_class_x]][1])&(weight<=weight_classes[[weight_class_x]][2]) - colors_points<-colors_f[[color_order[weight_class_x]]](length(z_plot_lines)*2-1)[(1:(length(z_plot_lines)-1))*2] - for (i in 1:(length(z_plot_lines)-1)) - { - tmp<-which((combined$z>=z_plot_lines[i])&(combined$z<=z_plot_lines[i+1])&weight_class_x_elements) - points(combined$y[tmp]~plot_x_function(combined$x[tmp]),pch=1,cex=0.5,col=colors_points[i]) - } - colors_startend<-colors_f[[color_order[weight_class_x]]](length(z_plot_lines)*2-1)[c(1,length(z_plot_lines)*2-1)] - points(combined$y[which(combined$z==z_plot_lines[1])]~plot_x_function(combined$x[which(combined$z==z_plot_lines[1])]),pch=1,cex=0.5,col=colors_startend[1]) - points(combined$y[which(combined$z==tail(z_plot_lines,n=1))]~plot_x_function(combined$x[which(combined$z==tail(z_plot_lines,n=1))]),pch=1,cex=0.5,col=colors_startend[2]) - } - } - - } - - transform_formula_to_function<-function(func,z){ - funcarguments<-all.vars(func)[-1] #names(formals(func)) - funcparas<-funcarguments[which(!funcarguments%in%c("x","y","z"))] - funcvars = all.vars(func)[-1][1] - if(length(func[[3]])>1) { - numberofparas=length(all.vars(func)[-1]) - if(numberofparas==1){numberofparas=2} - for (i in 2 : numberofparas) { - tmp=all.vars(func)[-1][i] - if(is.na(tmp)){tmp=NULL} - funcvars = c(funcvars,tmp) - } - if(!is.null(z)){ - if(!"z"%in%funcvars){funcvars<-c(funcvars,"z")} - } - } - if(length(func[[3]])==1) { - func=paste0("function(",paste0(funcvars,collapse = ","),"){",as.character(func[[3]]),"}") - } else { - func=paste0("function(",paste0(funcvars,collapse = ","),"){",format(func[[3]]),"}") - } - func=eval(parse(text=func)) - return(func) - } - - efrons_pseudo_r2<-function(model){ - pred <- predict(model) - n <- length(pred) - res <- resid(model) - w <- weights(model) - if (is.null(w)) w <- rep(1, n) - rss <- sum(w * res ^ 2) - resp <- pred + res - center <- weighted.mean(resp, w) - r.df <- summary(model)$df[2] - int.df <- 1 - tss <- sum(w * (resp - center)^2) - r.sq <- 1 - rss/tss - adj.r.sq <- 1 - (1 - r.sq) * (n - int.df) / r.df - out <- list(pseudo.R.squared = r.sq, - adj.R.squared = adj.r.sq) - return(out) - } - - - if(is.magpie(x)){x<-as.vector(x)} - if(is.magpie(y)){y<-as.vector(y)} - if(is.magpie(z)){z<-as.vector(z)} - if(is.magpie(weight)){weight<-as.vector(weight)} - - - if(plot_x_function!="ignore"){stop("argument plot_x_function is depreciated, please remove")} - if(x_log10==TRUE){ - plot_x_function=log10 - } else { - plot_x_function=function(x){x} - } - - - funcarguments<-all.vars(func)[-1] #names(formals(func)) - funcparas<-funcarguments[which(!funcarguments%in%c("x","y","z"))] - funcvars = all.vars(func)[-1][1] - - func <- transform_formula_to_function(func,z) - - - - # remove all NA - naVec = y * x - if (!is.null(z)) - { - naVec = naVec * z - } - if (!is.null(weight)) - { - if(!is.null(weight_threshold)){ - weight[weight3&length(summary(opt)$residual)<5000){ - norm_test <- shapiro.test(summary(opt)$residual)[["p.value"]] - } else { - norm_test <- NULL - } - # bp_test <- bptest(formula1,data=combined)[["p.value"]] - robust_out <- robust_vce(opt) - - prediction = predict(opt) - observation=y - lm_obs_vs_est = lm(prediction~observation,weights=weight) - - - ###R2 - # Coefficient of determination - pseudo_R2_unweighted <- max(cor(observation,prediction),0)^2 - pseudo_R2_weighted <- max(corr(matrix(data = c(observation,prediction),ncol = 2),w = combined$weight),0)^2 - pseudo_explained_sd = (var(observation)-var(prediction-observation))/var(observation) - efrons_r2 = efrons_pseudo_r2(opt) - - standarderror=(sum((prediction-observation)^2)/length(observation))^0.5 - - - ### transforming formulas into expression or functions - - formula2<-gsub(" ", "", format(func)[[3]], fixed = TRUE) - for (i in 1:length(funcparas)) { - formula2 <- gsub(funcparas[i], rounding_helper(para[i]), formula2, fixed = TRUE) - } - - function2<-eval(parse(text=paste0("y~",formula2))) - function2 <- transform_formula_to_function(function2,z) - - formula2<-paste0("y=",formula2) - - - returnvalue <- list(opt=opt, - coefficients=copt, - formula=formula2, - function2=function2, - lm_observed_vs_estimated=lm_obs_vs_est, - pseudo_R2_unweighted=pseudo_R2_unweighted, - efrons_weighted_r2=efrons_r2$pseudo.R.squared, - efrons_weighted_adj_r2=efrons_r2$adj.R.squared, - standarderror=standarderror, - observations = obs, - loglik = loglik, - norm_test = norm_test, - # bp_test = bp_test, - robust_out = robust_out - ) - - if(any(c("all","regression")%in%toPlot)) { - nlsplotlines(function2, - regressioncolor=regressioncolor, - z_plot_lines=z_plot_lines, - x_log10=x_log10) - } - - if(any(c("all","infos","infos1","infos2","infos3")%in%toPlot)) { - nlsplotinfos(combined=combined, - z_plot_lines=z_plot_lines, - plot_x_function=plot_x_function, - regressioncolor=regressioncolor, - returnvalue=returnvalue, - toPlot=toPlot) - } - - } else { - returnvalue <- list(modelVSdata="no fit", - opt="no fit",r2=0) - } - return(returnvalue) -} - - +#' @title nlsregression +#' +#' @description Creates regression parameter estimates and plots with any function you want +#' that has no more than two independent variables +#' +#' +#' @param func function that shall be fitted. Function should contain the +#' dependent variable y and and the independent variable x, eventually a second +#' independent variable z. All other unknowns are treated as parameters that +#' are estimated. +#' @param y dependent variable,vector +#' @param x independent variable,vector +#' @param z optional independent variable,vector +#' @param startvalues the optimization algorithm may require starting values +#' for the fitting procedure. provide them in a list with the parameter names: +#' e.g. list(a=3,b=2) +#' @param weight optional weight,vector +#' @param weighting if weighting is TRUE, the fit will minimize the weighted residuals +#' @param xlab name of x axis in plot +#' @param ylab name of y axis in plot +#' @param header plot function main argument +#' @param z_plot_lines vector>1 of values for z you want to be plotted into the +#' graph +#' @param weightcolorpoints if TRUE, the points are clustered into three +#' quantiles according to their weight and coloured lighter for low weights. +#' @param x_log10 allows log10 scale for X axis if set to TRUE. Only changes the picture, not +#' the regression! +#' @param plot_x_function depreciated, please do not enter into function call. +#' @param toPlot "all", "frame" (axis etc), "observations" (points), "regressionline" (line), "infos" (parameters, R2) +#' @param regressioncolor color of regression line and paramter text +#' @param weight_threshold if numeric, all countries below this threshold will be excluded (e.g. to exclude minor islands) +#' @param ... will be passed on to function nls +#' @return A nice picture and regression parameters or eventually some errors. +#' @author Benjamin Leon Bodirsky, Susanne Rolinski, Xiaoxi Wang +#' @examples +#' \dontrun{ +#' x=1:10 +#' y=(1:10)^2+1 +#' z=c(10:1) +#' +#' # one independent variable +#' nlsregression(func=y~a*x+b,y=y,x=x,startvalues=list(a=1,b=1)) +#' # two independent variables +#' nlsregression(func=y~a*x^1.1+b*z+c*x,y=y,x=x,z=z,startvalues=list(a=1,b=1,c=0)) +#' # no fit because residuals are zero (excluded from the nls makers due +#' to statistical reasons) +#' nlsregression(func=y~x^a+b,y=y,x=x,z=z,startvalues=list(a=1,b=1,c=0)) +#' +#' DNase1 <- subset(DNase, Run == 1) +#' DNase1$sets<- c(rep(1,8),rep(2,8)) +#' nlsregression(func=y~a*x+b,y=DNase1$density,x=DNase1$conc,startvalues=list(a=1,b=1)) +#' nlsregression(func=y~a*x+b*z,y=DNase1$density,x=DNase1$conc,z=DNase1$sets, +#' startvalues=list(a=0.1344,b=0.2597)) +#' nlsregression(func=y~a*x+b*z,y=DNase1$density,x=DNase1$conc,z=DNase1$sets, +#' startvalues=list(a=0.1344,b=0.2597),plot_x_function=log) +#' } +#' @export +#' @importFrom stats shapiro.test +#' @importFrom stats cor +#' @importFrom stats lm +#' @importFrom stats logLik +#' @importFrom stats nls +#' @importFrom stats predict +#' @importFrom stats resid +#' @importFrom stats var +#' @importFrom stats weighted.mean +#' @importFrom stats weights +#' @importFrom graphics plot abline legend lines points text curve +#' @importFrom grDevices colorRampPalette +#' @importFrom lmtest bptest +#' @importFrom boot corr +#' @importFrom nlstools confint2 + +nlsregression <- function(func, # y ~ a*x/b+x + y, x, z=NULL, + startvalues=NULL, + weight=NULL, + weighting=TRUE, + xlab=NULL, + ylab="y", + header=NULL, + z_plot_lines=NULL, + weightcolorpoints=TRUE, + x_log10=FALSE, + toPlot="all", + plot_x_function="ignore", + regressioncolor="blue", + weight_threshold=NULL, + ...) +{ + rounding_helper<-function(x) { + if ((x>1000)|(x< -1000)) { + x=format(signif(x,4), scientific=TRUE) + } else if ((x<0.01)&(x> -0.01)){ + x=format(signif(x,4), scientific=TRUE) + } else if(x>0){ + x<-format(signif(x,4), scientific=FALSE) + } + return(x) + } + + nlsplotlines<-function(function2,regressioncolor,z_plot_lines,x_log10){ + + if(x_log10==TRUE){ + revert=function(x){10^x} + }else { + revert=function(x){x} + } + if(is.null(z_plot_lines)) { + curve(function2(revert(x)),add = T,col=regressioncolor,lty=1,lwd=3) + } else { + for (i in 1:length(z_plot_lines)) { + curve(function2(revert(x),z=z_plot_lines[i]),add = T,col=regressioncolor[i],lty=1,lwd=3) + } + } + + + + } + + nlsplotinfos<-function(combined, z_plot_lines, plot_x_function, regressioncolor, returnvalue, toPlot){ + + if("infos1"%in%toPlot) { ### if several functions shall be plotted into the same plot + spacecorrection=0.05 + } else if ("infos2"%in%toPlot){ + spacecorrection=0.1 + } else if ("infos3"%in%toPlot){ + spacecorrection=0.15 + } else { + spacecorrection=0 + } + + if(!is.null(z_plot_lines)){ + text(labels = paste0("z:"), + col=regressioncolor, + x=min(plot_x_function(combined$x),na.rm=T), + y=max(combined$y,na.rm=T)*(0.9), + pos=4) + + for (i in 1:length(z_plot_lines)) { + text(labels = paste0(z_plot_lines[i]), + col=regressioncolor[i], + x=min(plot_x_function(combined$x),na.rm=T)+ + max(plot_x_function(combined$x),na.rm=T)*0.05, + y=max(combined$y,na.rm=T)*(0.95-(i*0.05)),pos=4) + } + } + + ###bottomright + text(labels = returnvalue$formula, + col=regressioncolor, + x=max(plot_x_function(combined$x),na.rm=T), + y=min(combined$y,na.rm=T)+ max(combined$y,na.rm=T)*spacecorrection, + pos=2) + + ### topleft + text(labels = paste0("Efron's weighted adj. R2: ", + round(returnvalue$efrons_weighted_adj_r2,2)), + col=regressioncolor, + x=min(plot_x_function(combined$x),na.rm=T), + y=max(combined$y*(1-spacecorrection),na.rm=T), + pos=4) + + ## topright + text(labels = paste0("S: ",rounding_helper(returnvalue$standarderror)), + col=regressioncolor, + x=max(plot_x_function(combined$x),na.rm=T), + y=max(combined$y*(1-spacecorrection),na.rm=T), + pos=2) + + #bottomleft + text(labels = paste0(returnvalue$observations," observations"), + col=regressioncolor, + x=min(plot_x_function(combined$x),na.rm=T), + y=min(combined$y,na.rm=T)+ max(combined$y,na.rm=T)*spacecorrection, + pos=4) + } + + nlsplotframe <- function(combined, xlab, ylab, plot_x_function, header){ + if(is.null(xlab)) { + if(is.primitive(plot_x_function)) { + #xlab=paste0(as.character(substitute(plot_x_function)),"(",xlab,")") + xlab=gsub(".Primitive(\"", "", format(plot_x_function), fixed = TRUE) + xlab=gsub("\")", "", xlab) + xlab<-paste0(xlab,"(x)") + } else { + xlab=gsub(" ", "", format(plot_x_function)[[3]], fixed = TRUE) + } + } + plot(combined$y~plot_x_function(combined$x),type="n", + xlab=xlab,ylab=ylab, + main=header) + } + + nlsplotpoints<-function(combined, plot_x_function, z_plot_lines, colors_f){ + + weight = combined$weight + + weight_classes<-list() + if(!all(weight==1)&(weightcolorpoints==TRUE)) { + weight_classes[[1]]<-quantile(weight,na.rm=T,probs=c(0,0.333)) + weight_classes[[2]]<-quantile(weight,na.rm=T,probs=c(0.333,0.666)) + weight_classes[[3]]<-quantile(weight,na.rm=T,probs=c(0.666,1)) + color_order=c(3,2,1) + } else { + weight_classes[[1]]<-quantile(weight,na.rm=T,probs=c(0,1)) + color_order=c(1) + } + + if(!("z"%in%names(combined))) { + colors_points=c("#000000","#595959","#ADADAD") + for (weight_class_x in (1:length(weight_classes))) { + weight_class_x_elements<-(weight>=weight_classes[[weight_class_x]][1])&(weight<=weight_classes[[weight_class_x]][2]) + tmp<-which(weight_class_x_elements) + points(combined$y[tmp]~plot_x_function(combined$x[tmp]),pch=1,cex=0.5,col=colors_points[color_order[weight_class_x]]) + } + }else { + + for (weight_class_x in (1:length(weight_classes))) { + weight_class_x_elements<-(weight>=weight_classes[[weight_class_x]][1])&(weight<=weight_classes[[weight_class_x]][2]) + colors_points<-colors_f[[color_order[weight_class_x]]](length(z_plot_lines)*2-1)[(1:(length(z_plot_lines)-1))*2] + for (i in 1:(length(z_plot_lines)-1)) + { + tmp<-which((combined$z>=z_plot_lines[i])&(combined$z<=z_plot_lines[i+1])&weight_class_x_elements) + points(combined$y[tmp]~plot_x_function(combined$x[tmp]),pch=1,cex=0.5,col=colors_points[i]) + } + colors_startend<-colors_f[[color_order[weight_class_x]]](length(z_plot_lines)*2-1)[c(1,length(z_plot_lines)*2-1)] + points(combined$y[which(combined$z==z_plot_lines[1])]~plot_x_function(combined$x[which(combined$z==z_plot_lines[1])]),pch=1,cex=0.5,col=colors_startend[1]) + points(combined$y[which(combined$z==tail(z_plot_lines,n=1))]~plot_x_function(combined$x[which(combined$z==tail(z_plot_lines,n=1))]),pch=1,cex=0.5,col=colors_startend[2]) + } + } + + } + + transform_formula_to_function<-function(func,z){ + funcarguments<-all.vars(func)[-1] #names(formals(func)) + funcparas<-funcarguments[which(!funcarguments%in%c("x","y","z"))] + funcvars = all.vars(func)[-1][1] + if(length(func[[3]])>1) { + numberofparas=length(all.vars(func)[-1]) + if(numberofparas==1){numberofparas=2} + for (i in 2 : numberofparas) { + tmp=all.vars(func)[-1][i] + if(is.na(tmp)){tmp=NULL} + funcvars = c(funcvars,tmp) + } + if(!is.null(z)){ + if(!"z"%in%funcvars){funcvars<-c(funcvars,"z")} + } + } + if(length(func[[3]])==1) { + func=paste0("function(",paste0(funcvars,collapse = ","),"){",as.character(func[[3]]),"}") + } else { + func=paste0("function(",paste0(funcvars,collapse = ","),"){",format(func[[3]]),"}") + } + func=eval(parse(text=func)) + return(func) + } + + efrons_pseudo_r2<-function(model){ + pred <- predict(model) + n <- length(pred) + res <- resid(model) + w <- weights(model) + if (is.null(w)) w <- rep(1, n) + rss <- sum(w * res ^ 2) + resp <- pred + res + center <- weighted.mean(resp, w) + r.df <- summary(model)$df[2] + int.df <- 1 + tss <- sum(w * (resp - center)^2) + r.sq <- 1 - rss/tss + adj.r.sq <- 1 - (1 - r.sq) * (n - int.df) / r.df + out <- list(pseudo.R.squared = r.sq, + adj.R.squared = adj.r.sq) + return(out) + } + + + if(is.magpie(x)){x<-as.vector(x)} + if(is.magpie(y)){y<-as.vector(y)} + if(is.magpie(z)){z<-as.vector(z)} + if(is.magpie(weight)){weight<-as.vector(weight)} + + + if(plot_x_function!="ignore"){stop("argument plot_x_function is depreciated, please remove")} + if(x_log10==TRUE){ + plot_x_function=log10 + } else { + plot_x_function=function(x){x} + } + + + funcarguments<-all.vars(func)[-1] #names(formals(func)) + funcparas<-funcarguments[which(!funcarguments%in%c("x","y","z"))] + funcvars = all.vars(func)[-1][1] + + func <- transform_formula_to_function(func,z) + + + + # remove all NA + naVec = y * x + if (!is.null(z)) + { + naVec = naVec * z + } + if (!is.null(weight)) + { + if(!is.null(weight_threshold)){ + weight[weight3&length(summary(opt)$residual)<5000){ + norm_test <- shapiro.test(summary(opt)$residual)[["p.value"]] + } else { + norm_test <- NULL + } + # bp_test <- bptest(formula1,data=combined)[["p.value"]] + robust_out <- robust_vce(opt) + + prediction = predict(opt) + observation=y + lm_obs_vs_est = lm(prediction~observation,weights=weight) + + + ###R2 + # Coefficient of determination + pseudo_R2_unweighted <- max(cor(observation,prediction),0)^2 + pseudo_R2_weighted <- max(corr(matrix(data = c(observation,prediction),ncol = 2),w = combined$weight),0)^2 + pseudo_explained_sd = (var(observation)-var(prediction-observation))/var(observation) + efrons_r2 = efrons_pseudo_r2(opt) + + standarderror=(sum((prediction-observation)^2)/length(observation))^0.5 + + + ### transforming formulas into expression or functions + + formula2<-gsub(" ", "", format(func)[[3]], fixed = TRUE) + for (i in 1:length(funcparas)) { + formula2 <- gsub(funcparas[i], rounding_helper(para[i]), formula2, fixed = TRUE) + } + + function2<-eval(parse(text=paste0("y~",formula2))) + function2 <- transform_formula_to_function(function2,z) + + formula2<-paste0("y=",formula2) + + + returnvalue <- list(opt=opt, + coefficients=copt, + formula=formula2, + function2=function2, + lm_observed_vs_estimated=lm_obs_vs_est, + pseudo_R2_unweighted=pseudo_R2_unweighted, + efrons_weighted_r2=efrons_r2$pseudo.R.squared, + efrons_weighted_adj_r2=efrons_r2$adj.R.squared, + standarderror=standarderror, + observations = obs, + loglik = loglik, + norm_test = norm_test, + # bp_test = bp_test, + robust_out = robust_out + ) + + if(any(c("all","regression")%in%toPlot)) { + nlsplotlines(function2, + regressioncolor=regressioncolor, + z_plot_lines=z_plot_lines, + x_log10=x_log10) + } + + if(any(c("all","infos","infos1","infos2","infos3")%in%toPlot)) { + nlsplotinfos(combined=combined, + z_plot_lines=z_plot_lines, + plot_x_function=plot_x_function, + regressioncolor=regressioncolor, + returnvalue=returnvalue, + toPlot=toPlot) + } + + } else { + returnvalue <- list(modelVSdata="no fit", + opt="no fit",r2=0) + } + return(returnvalue) +} + + diff --git a/R/robust_vce.R b/R/robust_vce.R index a4a7e5c..0427dd7 100644 --- a/R/robust_vce.R +++ b/R/robust_vce.R @@ -1,14 +1,14 @@ -#' @title robust_vce -#' @description returns robust var-cov estimate -#' @param x regression model -#' @return a robust estimte of variance-covariance matrix and corresponding t-value and p-value for estimated coefficients -#' @export -#' @importFrom sandwich sandwich -#' @importFrom lmtest coeftest -#' @author Xiaoxi Wang -#' -robust_vce <- function(x){ - covariance <- sandwich(x) - coef <- coeftest(x,covariance) - return(robust_estiamte =list(coef = coef, covariance = covariance)) +#' @title robust_vce +#' @description returns robust var-cov estimate +#' @param x regression model +#' @return a robust estimte of variance-covariance matrix and corresponding t-value and p-value for estimated coefficients +#' @export +#' @importFrom sandwich sandwich +#' @importFrom lmtest coeftest +#' @author Xiaoxi Wang +#' +robust_vce <- function(x){ + covariance <- sandwich(x) + coef <- coeftest(x,covariance) + return(robust_estiamte =list(coef = coef, covariance = covariance)) } \ No newline at end of file diff --git a/R/toolCollectRegressionVariables.R b/R/toolCollectRegressionVariables.R index 61d5eda..9a76a5d 100644 --- a/R/toolCollectRegressionVariables.R +++ b/R/toolCollectRegressionVariables.R @@ -1,173 +1,173 @@ -#' @title toolCollectRegressionVariables -#' @description todo -#' @param indicators todo -#' @return todo -#' @author Benjamin Leon Bodirsky -#' @export - -toolCollectRegressionVariables<-function(indicators){ - indicators<-unique(indicators) - - datasources=NULL - if (any(c("roundwood","wood","woodfuel") %in% indicators)) { - datasources=c(datasources,"wooddemand") - } - if ("forest_area" %in% indicators) { - datasources=c(datasources,"forest_area") - } - - if (any(c("Roundwood","Industrial roundwood","Wood fuel","Other industrial roundwood","Pulpwood", - "Sawlogs and veneer logs","Fibreboard","Particle board and OSB","Wood pulp","Sawnwood", - "Plywood","Veneer sheets","Wood-based panels" , - "Other sawnwood") %in% indicators)) { - datasources=c(datasources,"timber_demand") - } - - if ("urban" %in% indicators) { - datasources=c(datasources,"urbanization_WDI") - } - if ("pop" %in% indicators) { - datasources=c(datasources,"population_WDI") - } - if (any(c("ss_wood","ss_woodfuel") %in% indicators)) { - datasources=c(datasources,"SelfSuff") - } - if ("IHME_USD05_PPP_pc" %in% indicators) { - datasources=c(datasources,"gdp") - } - if (any(findset("kfo") %in% indicators)) { - datasources=c(datasources,"kcal") - } - if (any("kcal_last_20yrs" %in% indicators)) { - datasources=c(datasources,"kcal_last_20yrs") - } - if (any("batten_last_20yrs" %in% indicators)) { - datasources=c(datasources,"batten_last_20yrs") - } - if (any(c("inactivity_adults_M","inactivity_adults_F","inactivity_underaged_M","inactivity_underaged_F") %in% indicators)) { - datasources=c(datasources,"physical_inactivity") - } - if (any("overconsumption_last_20yrs" %in% indicators)) { - datasources=c(datasources,"overconsumption_last_20yrs") - } - - if (any(c("college","femcollege","low_education","below15","15-64","above64","femaleShare") %in% indicators)){ - datasources=c(datasources,"demographics") - } - if (any(c("climate") %in% indicators)) { - datasources=c(datasources,"climate") - } - if (any(c("intake_pc_schofield") %in% indicators)) { - datasources=c(datasources,"intake_pc_schofield") - } - if (any(c("intake_pc_FAO_WHO_UNU1985") %in% indicators)) { - datasources=c(datasources,"intake_pc_FAO_WHO_UNU1985") - } - if (any(c("intake_pc_Froehle") %in% indicators)) { - datasources=c(datasources,"intake_pc_Froehle") - } - if (any(c("intake_pc_FAO_WHO_UNU1985_M_old") %in% indicators)) { - datasources=c(datasources,"intake_pc_FAO_WHO_UNU1985_M_old") - } - if (any(c("intake_pc_FAO_WHO_UNU1985_F_old") %in% indicators)) { - datasources=c(datasources,"intake_pc_FAO_WHO_UNU1985_F_old") - } - if (any(c("intake_pc_FAO_WHO_UNU1985_M_underaged") %in% indicators)) { - datasources=c(datasources,"intake_pc_FAO_WHO_UNU1985_M_underaged") - } - if (any(c("intake_pc_FAO_WHO_UNU1985_F_underaged") %in% indicators)) { - datasources=c(datasources,"intake_pc_FAO_WHO_UNU1985_F_underaged") - } - if (any(c("intake_pc_FAO_WHO_UNU1985_M_working") %in% indicators)) { - datasources=c(datasources,"intake_pc_FAO_WHO_UNU1985_M_working") - } - if (any(c("intake_pc_FAO_WHO_UNU1985_F_working") %in% indicators)) { - datasources=c(datasources,"intake_pc_FAO_WHO_UNU1985_F_working") - } - if (any(c("intake_pc_standardized") %in% indicators)) { - datasources=c(datasources,"intake_pc_standardized") - } - if (any(c("intake_pc_standardized_BMI_FAO_WHO_UNU1985") %in% indicators)) { - datasources=c(datasources,"intake_pc_standardized_BMI_FAO_WHO_UNU1985") - } - if (any(c("intake_pc_standardized_BMI_FAO_WHO_UNU1985_M_working") %in% indicators)) { - datasources=c(datasources,"intake_pc_standardized_BMI_FAO_WHO_UNU1985_M_working") - } - if (any(c("intake_pc_standardized_BMI_FAO_WHO_UNU1985_F_working") %in% indicators)) { - datasources=c(datasources,"intake_pc_standardized_BMI_FAO_WHO_UNU1985_F_working") - } - if (any(c("intake_pc_standardized_BMI_FAO_WHO_UNU1985_M_underaged") %in% indicators)) { - datasources=c(datasources,"intake_pc_standardized_BMI_FAO_WHO_UNU1985_M_underaged") - } - if (any(c("intake_pc_standardized_BMI_FAO_WHO_UNU1985_F_underaged") %in% indicators)) { - datasources=c(datasources,"intake_pc_standardized_BMI_FAO_WHO_UNU1985_F_underaged") - } - if (any(c("intake_pc_standardized_BMI_FAO_WHO_UNU1985_M_old") %in% indicators)) { - datasources=c(datasources,"intake_pc_standardized_BMI_FAO_WHO_UNU1985_M_old") - } - if (any(c("intake_pc_standardized_BMI_FAO_WHO_UNU1985_F_old") %in% indicators)) { - datasources=c(datasources,"intake_pc_standardized_BMI_FAO_WHO_UNU1985_F_old") - } - if (any(c("bodyheight_M","bodyheight_F") %in% indicators)) { - datasources=c(datasources,"bodyheight") - } - - if (any(c("working_M_BMI_18-5","retired_M_BMI_18-5","working_M_BMI_18-5_20","retired_M_BMI_18-5_20", "working_M_BMI_20_25", - "retired_M_BMI_20_25","working_M_BMI_25_30","retired_M_BMI_25_30","working_M_BMI_30_35","retired_M_BMI_30_35", - "working_M_BMI_35_40","retired_M_BMI_35_40","working_M_BMI_40","retired_M_BMI_40","working_F_BMI_18-5", - "retired_F_BMI_18-5","working_F_BMI_18-5_20","retired_F_BMI_18-5_20","working_F_BMI_20_25","retired_F_BMI_20_25", - "working_F_BMI_25_30","retired_F_BMI_25_30","working_F_BMI_30_35","retired_F_BMI_30_35","working_F_BMI_35_40", - "retired_F_BMI_35_40","working_F_BMI_40","retired_F_BMI_40" - )%in% indicators)) { - datasources=c(datasources,"BMI_shr") - } - - if (any(c( "M_BMI_2sd","F_BMI_2sd","M_BMI_1sd_2sd", - "F_BMI_1sd_2sd","M_BMI_minus1sd_1sd","F_BMI_minus1sd_1sd", - "M_BMI_minus1sd_minus2sd","F_BMI_minus1sd_minus2sd","M_BMI_minus2sd", - "F_BMI_minus2sd" - )%in% indicators)) { - datasources=c(datasources,"BMI_shr_underaged") - } - - if (any(c( - "intake_F_0--4","intake_F_10--14","intake_F_100+","intake_F_15--19","intake_F_20--24", - "intake_F_25--29","intake_F_30--34","intake_F_35--39","intake_F_40--44","intake_F_45--49", - "intake_F_5--9","intake_F_50--54","intake_F_55--59","intake_F_60--64","intake_F_65--69", - "intake_F_70--74","intake_F_75--79","intake_F_80--84","intake_F_85--89","intake_F_90--94", - "intake_F_95--99","intake_F_All","intake_M_0--4","intake_M_10--14","intake_M_100+", - "intake_M_15--19","intake_M_20--24","intake_M_25--29","intake_M_30--34","intake_M_35--39", - "intake_M_40--44","intake_M_45--49","intake_M_5--9","intake_M_50--54","intake_M_55--59", - "intake_M_60--64","intake_M_65--69","intake_M_70--74","intake_M_75--79","intake_M_80--84", - "intake_M_85--89","intake_M_90--94","intake_M_95--99","intake_M_All" - ) %in% indicators)) { - datasources=c(datasources,"intake_demography") - } - - if (any(c( - "intake_standardized_F_0--4","intake_standardized_F_10--14","intake_standardized_F_100+","intake_standardized_F_15--19","intake_standardized_F_20--24", - "intake_standardized_F_25--29","intake_standardized_F_30--34","intake_standardized_F_35--39","intake_standardized_F_40--44","intake_standardized_F_45--49", - "intake_standardized_F_5--9","intake_standardized_F_50--54","intake_standardized_F_55--59","intake_standardized_F_60--64","intake_standardized_F_65--69", - "intake_standardized_F_70--74","intake_standardized_F_75--79","intake_standardized_F_80--84","intake_standardized_F_85--89","intake_standardized_F_90--94", - "intake_standardized_F_95--99","intake_standardized_F_All","intake_standardized_M_0--4","intake_standardized_M_10--14","intake_standardized_M_100+", - "intake_standardized_M_15--19","intake_standardized_M_20--24","intake_standardized_M_25--29","intake_standardized_M_30--34","intake_standardized_M_35--39", - "intake_standardized_M_40--44","intake_standardized_M_45--49","intake_standardized_M_5--9","intake_standardized_M_50--54","intake_standardized_M_55--59", - "intake_standardized_M_60--64","intake_standardized_M_65--69","intake_standardized_M_70--74","intake_standardized_M_75--79","intake_standardized_M_80--84", - "intake_standardized_M_85--89","intake_standardized_M_90--94","intake_standardized_M_95--99","intake_standardized_M_All" - ) %in% indicators)) { - datasources=c(datasources,"intake_standardized_demography") - } - - - data<-calcOutput("CollectRegressionData",datasources=datasources,aggregate = FALSE)[,,indicators] - #data<-calcOutput("CollectRegressionData",aggregate = FALSE) - - if(!all(indicators%in%getNames(data))){ - missing<-indicators[which(!indicators%in%getNames(data))] - missing<-findset(missing) - indicators<-c(missing,indicators[which(indicators%in%getNames(data))]) - } - - data<-data[,,indicators] - return(data) -} +#' @title toolCollectRegressionVariables +#' @description todo +#' @param indicators todo +#' @return todo +#' @author Benjamin Leon Bodirsky +#' @export + +toolCollectRegressionVariables<-function(indicators){ + indicators<-unique(indicators) + + datasources=NULL + if (any(c("roundwood","wood","woodfuel") %in% indicators)) { + datasources=c(datasources,"wooddemand") + } + if ("forest_area" %in% indicators) { + datasources=c(datasources,"forest_area") + } + + if (any(c("Roundwood","Industrial roundwood","Wood fuel","Other industrial roundwood","Pulpwood", + "Sawlogs and veneer logs","Fibreboard","Particle board and OSB","Wood pulp","Sawnwood", + "Plywood","Veneer sheets","Wood-based panels" , + "Other sawnwood") %in% indicators)) { + datasources=c(datasources,"timber_demand") + } + + if ("urban" %in% indicators) { + datasources=c(datasources,"urbanization_WDI") + } + if ("pop" %in% indicators) { + datasources=c(datasources,"population_WDI") + } + if (any(c("ss_wood","ss_woodfuel") %in% indicators)) { + datasources=c(datasources,"SelfSuff") + } + if ("IHME_USD05_PPP_pc" %in% indicators) { + datasources=c(datasources,"gdp") + } + if (any(findset("kfo") %in% indicators)) { + datasources=c(datasources,"kcal") + } + if (any("kcal_last_20yrs" %in% indicators)) { + datasources=c(datasources,"kcal_last_20yrs") + } + if (any("batten_last_20yrs" %in% indicators)) { + datasources=c(datasources,"batten_last_20yrs") + } + if (any(c("inactivity_adults_M","inactivity_adults_F","inactivity_underaged_M","inactivity_underaged_F") %in% indicators)) { + datasources=c(datasources,"physical_inactivity") + } + if (any("overconsumption_last_20yrs" %in% indicators)) { + datasources=c(datasources,"overconsumption_last_20yrs") + } + + if (any(c("college","femcollege","low_education","below15","15-64","above64","femaleShare") %in% indicators)){ + datasources=c(datasources,"demographics") + } + if (any(c("climate") %in% indicators)) { + datasources=c(datasources,"climate") + } + if (any(c("intake_pc_schofield") %in% indicators)) { + datasources=c(datasources,"intake_pc_schofield") + } + if (any(c("intake_pc_FAO_WHO_UNU1985") %in% indicators)) { + datasources=c(datasources,"intake_pc_FAO_WHO_UNU1985") + } + if (any(c("intake_pc_Froehle") %in% indicators)) { + datasources=c(datasources,"intake_pc_Froehle") + } + if (any(c("intake_pc_FAO_WHO_UNU1985_M_old") %in% indicators)) { + datasources=c(datasources,"intake_pc_FAO_WHO_UNU1985_M_old") + } + if (any(c("intake_pc_FAO_WHO_UNU1985_F_old") %in% indicators)) { + datasources=c(datasources,"intake_pc_FAO_WHO_UNU1985_F_old") + } + if (any(c("intake_pc_FAO_WHO_UNU1985_M_underaged") %in% indicators)) { + datasources=c(datasources,"intake_pc_FAO_WHO_UNU1985_M_underaged") + } + if (any(c("intake_pc_FAO_WHO_UNU1985_F_underaged") %in% indicators)) { + datasources=c(datasources,"intake_pc_FAO_WHO_UNU1985_F_underaged") + } + if (any(c("intake_pc_FAO_WHO_UNU1985_M_working") %in% indicators)) { + datasources=c(datasources,"intake_pc_FAO_WHO_UNU1985_M_working") + } + if (any(c("intake_pc_FAO_WHO_UNU1985_F_working") %in% indicators)) { + datasources=c(datasources,"intake_pc_FAO_WHO_UNU1985_F_working") + } + if (any(c("intake_pc_standardized") %in% indicators)) { + datasources=c(datasources,"intake_pc_standardized") + } + if (any(c("intake_pc_standardized_BMI_FAO_WHO_UNU1985") %in% indicators)) { + datasources=c(datasources,"intake_pc_standardized_BMI_FAO_WHO_UNU1985") + } + if (any(c("intake_pc_standardized_BMI_FAO_WHO_UNU1985_M_working") %in% indicators)) { + datasources=c(datasources,"intake_pc_standardized_BMI_FAO_WHO_UNU1985_M_working") + } + if (any(c("intake_pc_standardized_BMI_FAO_WHO_UNU1985_F_working") %in% indicators)) { + datasources=c(datasources,"intake_pc_standardized_BMI_FAO_WHO_UNU1985_F_working") + } + if (any(c("intake_pc_standardized_BMI_FAO_WHO_UNU1985_M_underaged") %in% indicators)) { + datasources=c(datasources,"intake_pc_standardized_BMI_FAO_WHO_UNU1985_M_underaged") + } + if (any(c("intake_pc_standardized_BMI_FAO_WHO_UNU1985_F_underaged") %in% indicators)) { + datasources=c(datasources,"intake_pc_standardized_BMI_FAO_WHO_UNU1985_F_underaged") + } + if (any(c("intake_pc_standardized_BMI_FAO_WHO_UNU1985_M_old") %in% indicators)) { + datasources=c(datasources,"intake_pc_standardized_BMI_FAO_WHO_UNU1985_M_old") + } + if (any(c("intake_pc_standardized_BMI_FAO_WHO_UNU1985_F_old") %in% indicators)) { + datasources=c(datasources,"intake_pc_standardized_BMI_FAO_WHO_UNU1985_F_old") + } + if (any(c("bodyheight_M","bodyheight_F") %in% indicators)) { + datasources=c(datasources,"bodyheight") + } + + if (any(c("working_M_BMI_18-5","retired_M_BMI_18-5","working_M_BMI_18-5_20","retired_M_BMI_18-5_20", "working_M_BMI_20_25", + "retired_M_BMI_20_25","working_M_BMI_25_30","retired_M_BMI_25_30","working_M_BMI_30_35","retired_M_BMI_30_35", + "working_M_BMI_35_40","retired_M_BMI_35_40","working_M_BMI_40","retired_M_BMI_40","working_F_BMI_18-5", + "retired_F_BMI_18-5","working_F_BMI_18-5_20","retired_F_BMI_18-5_20","working_F_BMI_20_25","retired_F_BMI_20_25", + "working_F_BMI_25_30","retired_F_BMI_25_30","working_F_BMI_30_35","retired_F_BMI_30_35","working_F_BMI_35_40", + "retired_F_BMI_35_40","working_F_BMI_40","retired_F_BMI_40" + )%in% indicators)) { + datasources=c(datasources,"BMI_shr") + } + + if (any(c( "M_BMI_2sd","F_BMI_2sd","M_BMI_1sd_2sd", + "F_BMI_1sd_2sd","M_BMI_minus1sd_1sd","F_BMI_minus1sd_1sd", + "M_BMI_minus1sd_minus2sd","F_BMI_minus1sd_minus2sd","M_BMI_minus2sd", + "F_BMI_minus2sd" + )%in% indicators)) { + datasources=c(datasources,"BMI_shr_underaged") + } + + if (any(c( + "intake_F_0--4","intake_F_10--14","intake_F_100+","intake_F_15--19","intake_F_20--24", + "intake_F_25--29","intake_F_30--34","intake_F_35--39","intake_F_40--44","intake_F_45--49", + "intake_F_5--9","intake_F_50--54","intake_F_55--59","intake_F_60--64","intake_F_65--69", + "intake_F_70--74","intake_F_75--79","intake_F_80--84","intake_F_85--89","intake_F_90--94", + "intake_F_95--99","intake_F_All","intake_M_0--4","intake_M_10--14","intake_M_100+", + "intake_M_15--19","intake_M_20--24","intake_M_25--29","intake_M_30--34","intake_M_35--39", + "intake_M_40--44","intake_M_45--49","intake_M_5--9","intake_M_50--54","intake_M_55--59", + "intake_M_60--64","intake_M_65--69","intake_M_70--74","intake_M_75--79","intake_M_80--84", + "intake_M_85--89","intake_M_90--94","intake_M_95--99","intake_M_All" + ) %in% indicators)) { + datasources=c(datasources,"intake_demography") + } + + if (any(c( + "intake_standardized_F_0--4","intake_standardized_F_10--14","intake_standardized_F_100+","intake_standardized_F_15--19","intake_standardized_F_20--24", + "intake_standardized_F_25--29","intake_standardized_F_30--34","intake_standardized_F_35--39","intake_standardized_F_40--44","intake_standardized_F_45--49", + "intake_standardized_F_5--9","intake_standardized_F_50--54","intake_standardized_F_55--59","intake_standardized_F_60--64","intake_standardized_F_65--69", + "intake_standardized_F_70--74","intake_standardized_F_75--79","intake_standardized_F_80--84","intake_standardized_F_85--89","intake_standardized_F_90--94", + "intake_standardized_F_95--99","intake_standardized_F_All","intake_standardized_M_0--4","intake_standardized_M_10--14","intake_standardized_M_100+", + "intake_standardized_M_15--19","intake_standardized_M_20--24","intake_standardized_M_25--29","intake_standardized_M_30--34","intake_standardized_M_35--39", + "intake_standardized_M_40--44","intake_standardized_M_45--49","intake_standardized_M_5--9","intake_standardized_M_50--54","intake_standardized_M_55--59", + "intake_standardized_M_60--64","intake_standardized_M_65--69","intake_standardized_M_70--74","intake_standardized_M_75--79","intake_standardized_M_80--84", + "intake_standardized_M_85--89","intake_standardized_M_90--94","intake_standardized_M_95--99","intake_standardized_M_All" + ) %in% indicators)) { + datasources=c(datasources,"intake_standardized_demography") + } + + + data<-calcOutput("CollectRegressionData",datasources=datasources,aggregate = FALSE)[,,indicators] + #data<-calcOutput("CollectRegressionData",aggregate = FALSE) + + if(!all(indicators%in%getNames(data))){ + missing<-indicators[which(!indicators%in%getNames(data))] + missing<-findset(missing) + indicators<-c(missing,indicators[which(indicators%in%getNames(data))]) + } + + data<-data[,,indicators] + return(data) +} diff --git a/R/toolRegression.R b/R/toolRegression.R index 17f6b50..d9e90b3 100644 --- a/R/toolRegression.R +++ b/R/toolRegression.R @@ -1,157 +1,157 @@ -#' @title toolRegression -#' @description Regression model for the correlation of a denominator and quotient to the GDP, allowing for an additional driver z next to income. -#' -#' @param denominator denominator of the dependent variable that shall be estimated using the regression -#' @param quotient quotient of the dependent variable that shall be estimated using the regression -#' @param func functional relation for the regression, shall be in the format y~f(x,...) with x being gdp, y being denominator/quotient, and f() being any type of functional relationship. ... can inlcude either z or parameters to be estimated. -#' @param x independet variable, by default income -#' @param z additional independet variable -#' @param xlab name of x axis -#' @param ylab name of y axis -#' @param data data can be provided if Data shall not be derived by moinput:::calcCollectFoodDemandRegressionData() -#' @param countries_nlsAddLines the number of weightiest countries or the name of countries that shall be plotted by lines in the plot -#' @param weight the weight -#' @param x_log10 passed on to nlsregression() -#' @param ... further attributes that will be handed on to nlsregression(): -#' -#' An additional explanatory variable z can be added. -#' A regression model has to be chosen. -#' Startvalues can be predetermained. -#' -#' @return regression plot and the parameters from nlsregression -#' @author Antonia Walther, Benjamin Leon Bodirsky -#' -#' -#' -#' @seealso \code{\link{calcOutput}} -#' @examples -#' -#' \dontrun{ -#' -#' toolRegression(denominator=livestock, -#' func=y~(a*x)/(b+x), -#' z=NULL, -#' startvalues=list(a=1100,b=7770) -#' ) -#' -#' toolRegression(denominator=findset("kap"), -#' quotient=findset("kfo"), -#' func=y~(a*x)/(b+x), -#' z=NULL, -#' startvalues=list(a=0.5,b=7770) -#' ) -#' -#' } -#' @importFrom magpiesets findset -#' @importFrom RColorBrewer brewer.pal.info brewer.pal -#' -#' @export - -toolRegression<-function(denominator, - quotient = NULL, - func=y~(a*x)/(b+x), - x="IHME_USD05_PPP_pc", - z=NULL, - ylab = NULL, - xlab=NULL, - data = NULL, - countries_nlsAddLines=NULL, - weight="pop", - x_log10=FALSE, - ... - ) -{ - if (is.null(data)){ - data<-toolCollectRegressionVariables(indicators=c(denominator,quotient,x,z,weight)) - } - - if(is.null(xlab)){ - if(length(x)>1){ - xlab<-deparse(substitute(x)) - }else { - xlab<-x - } - } - - denom_name <- deparse(substitute(denominator)) - quot_name <- deparse(substitute(quotient)) - - if(!all(denominator%in%getNames(data))){ - denominator <- eval(parse(text = denominator)) - denom<-findset(denominator) - } else { - denom=denominator - } - - if(!all(quotient%in%getNames(data))){ - quotient <- eval(parse(text = quotient)) - quot<- findset(quotient) - } else { - quot=quotient - } - - - if(is.null(quotient)){ - quot=1 - } else { - quot = dimSums(data[,,quot],dim=3) - } - - if(is.null(weight)){ - weight=1 - } else { - weight = dimSums(data[,,weight],dim=3) - } - - denom = dimSums(data[,,denom],dim=3) - - #gdp per capita ausrechnen und z(urban oder education shr) ausrechnen - driv1<-dimSums(data[,,x],dim=3) - - if(length(x)>1){driv1=dimSums(driv1,dim=3)} - - if(is.null(z)) - { - driv2 <- NULL - } else { - driv2<-data[,,z] - } - - if (is.null(ylab)) - { - if(!is.null(quotient)){ - ylab <- paste("(",denom_name,")/(",quot_name,")") - } else { - ylab <- paste(denom_name) - } - } - - - out<-nlsregression( - func=func, - y=as.vector(denom/quot), - x=as.vector(driv1), - z=as.vector(driv2), - weight = as.vector(weight), - xlab=xlab, - ylab=ylab, - x_log10=x_log10, - ... - ) - - if(!is.null(countries_nlsAddLines)){ - - # nice color algorithm from Jelena-bioinf in stackoverflow - n <- length(countries_nlsAddLines) - qual_col_pals = brewer.pal.info[brewer.pal.info$category == 'qual',] - col_vector = unlist(mapply(brewer.pal, qual_col_pals$maxcolors, rownames(qual_col_pals))) - - nlsAddLines(y = denom/quot, - x=driv1, - weight=weight, - countries = countries_nlsAddLines, - colors = col_vector, - x_log10=x_log10) - } - return(out) -} +#' @title toolRegression +#' @description Regression model for the correlation of a denominator and quotient to the GDP, allowing for an additional driver z next to income. +#' +#' @param denominator denominator of the dependent variable that shall be estimated using the regression +#' @param quotient quotient of the dependent variable that shall be estimated using the regression +#' @param func functional relation for the regression, shall be in the format y~f(x,...) with x being gdp, y being denominator/quotient, and f() being any type of functional relationship. ... can inlcude either z or parameters to be estimated. +#' @param x independet variable, by default income +#' @param z additional independet variable +#' @param xlab name of x axis +#' @param ylab name of y axis +#' @param data data can be provided if Data shall not be derived by moinput:::calcCollectFoodDemandRegressionData() +#' @param countries_nlsAddLines the number of weightiest countries or the name of countries that shall be plotted by lines in the plot +#' @param weight the weight +#' @param x_log10 passed on to nlsregression() +#' @param ... further attributes that will be handed on to nlsregression(): +#' +#' An additional explanatory variable z can be added. +#' A regression model has to be chosen. +#' Startvalues can be predetermained. +#' +#' @return regression plot and the parameters from nlsregression +#' @author Antonia Walther, Benjamin Leon Bodirsky +#' +#' +#' +#' @seealso \code{\link{calcOutput}} +#' @examples +#' +#' \dontrun{ +#' +#' toolRegression(denominator=livestock, +#' func=y~(a*x)/(b+x), +#' z=NULL, +#' startvalues=list(a=1100,b=7770) +#' ) +#' +#' toolRegression(denominator=findset("kap"), +#' quotient=findset("kfo"), +#' func=y~(a*x)/(b+x), +#' z=NULL, +#' startvalues=list(a=0.5,b=7770) +#' ) +#' +#' } +#' @importFrom magpiesets findset +#' @importFrom RColorBrewer brewer.pal.info brewer.pal +#' +#' @export + +toolRegression<-function(denominator, + quotient = NULL, + func=y~(a*x)/(b+x), + x="IHME_USD05_PPP_pc", + z=NULL, + ylab = NULL, + xlab=NULL, + data = NULL, + countries_nlsAddLines=NULL, + weight="pop", + x_log10=FALSE, + ... + ) +{ + if (is.null(data)){ + data<-toolCollectRegressionVariables(indicators=c(denominator,quotient,x,z,weight)) + } + + if(is.null(xlab)){ + if(length(x)>1){ + xlab<-deparse(substitute(x)) + }else { + xlab<-x + } + } + + denom_name <- deparse(substitute(denominator)) + quot_name <- deparse(substitute(quotient)) + + if(!all(denominator%in%getNames(data))){ + denominator <- eval(parse(text = denominator)) + denom<-findset(denominator) + } else { + denom=denominator + } + + if(!all(quotient%in%getNames(data))){ + quotient <- eval(parse(text = quotient)) + quot<- findset(quotient) + } else { + quot=quotient + } + + + if(is.null(quotient)){ + quot=1 + } else { + quot = dimSums(data[,,quot],dim=3) + } + + if(is.null(weight)){ + weight=1 + } else { + weight = dimSums(data[,,weight],dim=3) + } + + denom = dimSums(data[,,denom],dim=3) + + #gdp per capita ausrechnen und z(urban oder education shr) ausrechnen + driv1<-dimSums(data[,,x],dim=3) + + if(length(x)>1){driv1=dimSums(driv1,dim=3)} + + if(is.null(z)) + { + driv2 <- NULL + } else { + driv2<-data[,,z] + } + + if (is.null(ylab)) + { + if(!is.null(quotient)){ + ylab <- paste("(",denom_name,")/(",quot_name,")") + } else { + ylab <- paste(denom_name) + } + } + + + out<-nlsregression( + func=func, + y=as.vector(denom/quot), + x=as.vector(driv1), + z=as.vector(driv2), + weight = as.vector(weight), + xlab=xlab, + ylab=ylab, + x_log10=x_log10, + ... + ) + + if(!is.null(countries_nlsAddLines)){ + + # nice color algorithm from Jelena-bioinf in stackoverflow + n <- length(countries_nlsAddLines) + qual_col_pals = brewer.pal.info[brewer.pal.info$category == 'qual',] + col_vector = unlist(mapply(brewer.pal, qual_col_pals$maxcolors, rownames(qual_col_pals))) + + nlsAddLines(y = denom/quot, + x=driv1, + weight=weight, + countries = countries_nlsAddLines, + colors = col_vector, + x_log10=x_log10) + } + return(out) +} diff --git a/R/toolRegressionTable.R b/R/toolRegressionTable.R index 8c6f0e7..a806427 100644 --- a/R/toolRegressionTable.R +++ b/R/toolRegressionTable.R @@ -1,136 +1,136 @@ -#' @title toolRegressionTable -#' @description creates Regression for selected options and saves calculated parametes inside the table. -#' -#' @param scenario vector. Default "SSP2". Can be "SSP1", "SSP2", "SSP3", "SSP4", "SSP5" or "mix" and describes the overall scenario of the projection. -#' @param x Indep Var -#' @param denominator vector. Default NA. Specific fooddenominator share to make projection for. -#' @param quotient vector. Default is population ("pop") -#' @param z other independent variables -#' @param start_1 Default NA. Startvalue for 1st parameter. -#' @param start_2 Default NA. Startvalue for 2nd parameter. -#' @param start_3 Default NA. Startvalue for 3rd parameter. -#' @param start_4 Default NA. Startvalue for 4th parameter. -#' @param start_5 Default NA. Startvalue for 5th parameter. -#' @param start_6 Default NA. Startvalue for 6th parameter. -#' @param regression_database_file file with regressions to calculate -#' @param return_value Default to False. This is to stop printing the updated dataset on console. If you'd like to keep the updated dataset as an object, set this to true. -#' -#' @return data frame with additional rows containing parameters of newly calculated regression. -#' @author Abhijeet Mishra, Eleonora Martinelli -#' -#' @import utils -#' @importFrom stats as.formula -#' @seealso \code{\link{toolRegression}} -#' @export - -toolRegressionTable <- function( scenario="SSP2", - x="IHME_USD05_PPP_pc", - denominator=NA, - z=NA, - regression_database_file = "scenario_database_mrregression.csv", - quotient = "pop", - start_1 = NA, - start_2 = NA, - start_3 = NA, - start_4 = NA, - start_5 = NA, - start_6 = NA, - return_value=FALSE) -{ - t1 <- Sys.time() - table_database <- toolMappingFile(type = "settings",name= regression_database_file,readcsv = T) - - table <- table_database - x_IndepVar <- x - - toPlot=TRUE - - version <- gsub(pattern = "-",replacement = "",Sys.time()) - version <- gsub(pattern = " ",replacement = "_",version) - version <- gsub(pattern = ":",replacement = "",version) - - - new_table <- table - - for (i in 1:nrow(table)) - { - print(paste(i, "of", nrow(table))) - - denom <- denominator - quot <- quotient - - weight <- table[i,"weight"] - if (is.null(weight)) { - weight <- quot - } - if(!denom %in% unique(table$denominator)) - { - denominator = eval(denom) - } else { - denominator = denom - } - if(quot=="NULL"){ - quotient<-NULL - } else { - if(!quot %in% getNames(data)) - { - quotient = eval(quot) - } else { - quotient = quot - } - - } - - func <- as.formula(table[i,"functional_form"]) - yname <- paste(denom,"per",quot) - - if(denom == "kfo"){ - denominator <- findset(denom) - } - - if(quot == "kfo"){ - quotient <- findset(quot) - } - - regrData <- toolRegression(denominator,quotient,func=func, - x = x,weight=weight,ylab = yname,toPlot=toPlot) - - if (regrData[1]=="no fit") - { - allParas <-rep("no fit",6) - R2 <- "no fit" - R2adj <- "no fit" - } else { - allParas <-rep(NA,6) - for (i_para in 1:6) - { - allParas[i_para] <- regrData$opt$m$getPars()[i_para] - } - R2 <- regrData$modelVSdata[8] - R2adj <- regrData$modelVSdata[9] - } - - if (x_IndepVar == "IHME_USD05_PPP_pc"){ - x_IndepVar <- "gdp" - } - para_start_index <- which(colnames(new_table)=="para_1") - para_end_index <- which(colnames(new_table)=="para_6") - - newRow <- unlist(c(paste0(x_IndepVar,"_",version),scenario,denom,quot,new_table[i,"functional_form"],z, - allParas, - R2,R2adj, - new_table[i,para_start_index:para_end_index])) - new_table <- rbind(new_table, newRow) - } - new_table <- rbind(table_database,new_table) - new_table = unique(new_table) - - filename <- paste0(getConfig("mappingfolder"),"/settings/",regression_database_file) - write.csv(new_table,filename, row.names = FALSE,quote = F) - - t2 <- Sys.time() - cat("\nDatabase updated successfully in",round(t2-t1,digits = 2),"seconds.\n") - if(return_value){ - return(new_table) - } -} +#' @title toolRegressionTable +#' @description creates Regression for selected options and saves calculated parametes inside the table. +#' +#' @param scenario vector. Default "SSP2". Can be "SSP1", "SSP2", "SSP3", "SSP4", "SSP5" or "mix" and describes the overall scenario of the projection. +#' @param x Indep Var +#' @param denominator vector. Default NA. Specific fooddenominator share to make projection for. +#' @param quotient vector. Default is population ("pop") +#' @param z other independent variables +#' @param start_1 Default NA. Startvalue for 1st parameter. +#' @param start_2 Default NA. Startvalue for 2nd parameter. +#' @param start_3 Default NA. Startvalue for 3rd parameter. +#' @param start_4 Default NA. Startvalue for 4th parameter. +#' @param start_5 Default NA. Startvalue for 5th parameter. +#' @param start_6 Default NA. Startvalue for 6th parameter. +#' @param regression_database_file file with regressions to calculate +#' @param return_value Default to False. This is to stop printing the updated dataset on console. If you'd like to keep the updated dataset as an object, set this to true. +#' +#' @return data frame with additional rows containing parameters of newly calculated regression. +#' @author Abhijeet Mishra, Eleonora Martinelli +#' +#' @import utils +#' @importFrom stats as.formula +#' @seealso \code{\link{toolRegression}} +#' @export + +toolRegressionTable <- function( scenario="SSP2", + x="IHME_USD05_PPP_pc", + denominator=NA, + z=NA, + regression_database_file = "scenario_database_mrregression.csv", + quotient = "pop", + start_1 = NA, + start_2 = NA, + start_3 = NA, + start_4 = NA, + start_5 = NA, + start_6 = NA, + return_value=FALSE) +{ + t1 <- Sys.time() + table_database <- toolMappingFile(type = "settings",name= regression_database_file,readcsv = T) + + table <- table_database + x_IndepVar <- x + + toPlot=TRUE + + version <- gsub(pattern = "-",replacement = "",Sys.time()) + version <- gsub(pattern = " ",replacement = "_",version) + version <- gsub(pattern = ":",replacement = "",version) + + + new_table <- table + + for (i in 1:nrow(table)) + { + print(paste(i, "of", nrow(table))) + + denom <- denominator + quot <- quotient + + weight <- table[i,"weight"] + if (is.null(weight)) { + weight <- quot + } + if(!denom %in% unique(table$denominator)) + { + denominator = eval(denom) + } else { + denominator = denom + } + if(quot=="NULL"){ + quotient<-NULL + } else { + if(!quot %in% getNames(data)) + { + quotient = eval(quot) + } else { + quotient = quot + } + + } + + func <- as.formula(table[i,"functional_form"]) + yname <- paste(denom,"per",quot) + + if(denom == "kfo"){ + denominator <- findset(denom) + } + + if(quot == "kfo"){ + quotient <- findset(quot) + } + + regrData <- toolRegression(denominator,quotient,func=func, + x = x,weight=weight,ylab = yname,toPlot=toPlot) + + if (regrData[1]=="no fit") + { + allParas <-rep("no fit",6) + R2 <- "no fit" + R2adj <- "no fit" + } else { + allParas <-rep(NA,6) + for (i_para in 1:6) + { + allParas[i_para] <- regrData$opt$m$getPars()[i_para] + } + R2 <- regrData$modelVSdata[8] + R2adj <- regrData$modelVSdata[9] + } + + if (x_IndepVar == "IHME_USD05_PPP_pc"){ + x_IndepVar <- "gdp" + } + para_start_index <- which(colnames(new_table)=="para_1") + para_end_index <- which(colnames(new_table)=="para_6") + + newRow <- unlist(c(paste0(x_IndepVar,"_",version),scenario,denom,quot,new_table[i,"functional_form"],z, + allParas, + R2,R2adj, + new_table[i,para_start_index:para_end_index])) + new_table <- rbind(new_table, newRow) + } + new_table <- rbind(table_database,new_table) + new_table = unique(new_table) + + filename <- paste0(getConfig("mappingfolder"),"/settings/",regression_database_file) + write.csv(new_table,filename, row.names = FALSE,quote = F) + + t2 <- Sys.time() + cat("\nDatabase updated successfully in",round(t2-t1,digits = 2),"seconds.\n") + if(return_value){ + return(new_table) + } +} diff --git a/mrregression.Rproj b/mrregression.Rproj index 8cc08ce..1788e68 100644 --- a/mrregression.Rproj +++ b/mrregression.Rproj @@ -1,18 +1,18 @@ -Version: 1.0 - -RestoreWorkspace: Default -SaveWorkspace: Default -AlwaysSaveHistory: Default - -EnableCodeIndexing: Yes -UseSpacesForTab: Yes -NumSpacesForTab: 2 -Encoding: UTF-8 - -RnwWeave: Sweave -LaTeX: pdfLaTeX - -BuildType: Package -PackageUseDevtools: Yes -PackageInstallArgs: --no-multiarch --with-keep.source -PackageRoxygenize: rd,collate,namespace,vignette +Version: 1.0 + +RestoreWorkspace: Default +SaveWorkspace: Default +AlwaysSaveHistory: Default + +EnableCodeIndexing: Yes +UseSpacesForTab: Yes +NumSpacesForTab: 2 +Encoding: UTF-8 + +RnwWeave: Sweave +LaTeX: pdfLaTeX + +BuildType: Package +PackageUseDevtools: Yes +PackageInstallArgs: --no-multiarch --with-keep.source +PackageRoxygenize: rd,collate,namespace,vignette