├── .gitignore ├── Course 1 - Basic Data Manipulation and Visualization in R ├── Archive │ ├── C1_S1_HW_more_EX.R │ ├── C1_S1_in_class - Golf Hotel.R │ └── Macro-Data-Portal Excercise.R ├── BaseGraphicsCheatsheet.pdf ├── C1_S1.R ├── C1_S1_HW.R ├── C1_S1_HW_SOL.R ├── C1_S1_ICE_SOL.R ├── C1_S2.R ├── C1_S2_HW.R ├── C1_S2_ICE_SOL.R ├── base-r.pdf ├── data │ ├── Amount_of_Water_Supplied_and_Billing_efficiency_by_NWSC.csv │ ├── Pupil_Teacher_Ratio_by_District.xlsx │ └── sachs 2003 institutions don't rule.dta └── figures │ ├── ptr_district_dotchart.pdf │ ├── ptr_year_barplot.pdf │ └── superheat.pdf ├── Course 2 - Advanced Data Manipulation and Visualization in R ├── C2_S1.R ├── C2_S1_ICE_SOL.R ├── C2_S2.R ├── cheatsheets │ ├── collapse.pdf │ ├── datatable.pdf │ └── ggplot2.pdf ├── data │ ├── Ag_SAM_modified.xlsx │ ├── BOU_MMI.xlsx │ ├── BOU_MMI_labels.xlsx │ ├── UBOS 2014 Census.rds │ ├── UNHS_pov16.dta │ └── plotdata │ │ ├── 2 Extra attainment indicators from WDI.dta │ │ ├── Data_Extract_From_Education_Statistics_-_All_Indicators.xlsx │ │ ├── Governance, Uganda + Regional Aggregates, 2010-2016 Average.dta │ │ ├── HDI Trends.dta │ │ ├── Schools.xlsx │ │ ├── UNESCO UIS Download.csv │ │ ├── Uganda Districts Shapefile │ │ ├── Districts_2014_UBOS.cpg │ │ ├── Districts_2014_UBOS.dbf │ │ ├── Districts_2014_UBOS.prj │ │ ├── Districts_2014_UBOS.shp │ │ ├── Districts_2014_UBOS.shp.xml │ │ └── Districts_2014_UBOS.shx │ │ └── ltgraphGEOdetailed.csv └── figures │ ├── HDI Trends.pdf │ ├── R colors.pdf │ ├── Schools and Population Choropleth.pdf │ ├── Schools by Size Map FINAL.pdf │ ├── Schools by Size Map.pdf │ ├── Uganda Education Trends 1.pdf │ ├── Uganda Education Trends 2.pdf │ ├── Uganda Governance Statistics.pdf │ └── World Wealth and Human Development.pdf ├── Course 3 - Linear Modelling and Analysis + Extensions in R ├── C3_S1.R ├── C3_S2.R ├── Econometrics Academy │ ├── Instrumental Variables │ │ ├── Bachelor Level │ │ │ ├── Instrumental Variables Example.pdf │ │ │ ├── Instrumental Variables R Program and Output.pdf │ │ │ ├── Instrumental Variables in R.R │ │ │ ├── Instrumental Variables.pdf │ │ │ └── iv_health.csv │ │ └── Master Level │ │ │ ├── 15 Instrumental Variables.R │ │ │ ├── 15 Instrumental Variables.pdf │ │ │ └── MROZ.csv │ ├── Linear Regression │ │ ├── Bachelor Level │ │ │ ├── Linear Regression Example.pdf │ │ │ ├── Linear Regression R Program and Output.pdf │ │ │ ├── Linear Regression in R.R │ │ │ ├── Linear Regression.pdf │ │ │ └── regression_auto.csv │ │ └── Master Level │ │ │ ├── 3 Multiple Regression Model.R │ │ │ ├── 3 Multiple Regression Model.pdf │ │ │ ├── CEOSAL1.csv │ │ │ ├── HTV.csv │ │ │ ├── elemapi2.csv │ │ │ └── wage1.csv │ ├── Panel Data Models │ │ ├── Bachelor Level │ │ │ ├── Panel Data Models Example.pdf │ │ │ ├── Panel Data Models R Program and Output.pdf │ │ │ ├── Panel Data Models in R.R │ │ │ ├── Panel Data Models.pdf │ │ │ └── panel_wage.csv │ │ └── Master Level │ │ │ ├── 14 Panel Data Model.R │ │ │ ├── 14 Panel Data Models.pdf │ │ │ └── JTRAIN.csv │ └── Probit and Logit Models │ │ ├── Bachelor level │ │ ├── Probit and Logit Models Example.pdf │ │ ├── Probit and Logit Models R Program and Output.pdf │ │ ├── Probit and Logit Models in R.R │ │ ├── Probit and Logit Models.pdf │ │ └── probit_insurance.csv │ │ └── Master Level │ │ ├── 17 Probit and Logit Models.R │ │ ├── 17 Probit and Logit Models.pdf │ │ └── MROZ.csv ├── factors.pdf ├── logmodels2.pdf └── probability-statistics.pdf ├── Course 4 - Time Series Analysis and Forecasting in R ├── C4_S1.R ├── C4_S1_ICE_SOL.R ├── C4_S2.R ├── data │ └── exercise1.xlsx └── resources │ ├── ARMA Selection.PNG │ ├── Forecasting with R Data Camp Course Slides │ ├── chapter1.pdf │ ├── chapter2.pdf │ ├── chapter3.pdf │ ├── chapter4.pdf │ └── chapter5.pdf │ ├── Macroeconomic Forecasting with ECM's and DLM's │ ├── GDP_REV_Q.xlsx │ ├── ME_FC_ECM_DLM.Rmd │ ├── ME_FC_ECM_DLM_PCK_FUN.R │ └── Macroeconomic Forecasting with ECM and DLM.pdf │ └── Testing for Unit Roots.PNG ├── Course 6 - Computable Documents and Interactive Dashboards in R ├── C6_S1.R ├── C6_S2.R ├── Computable POE │ ├── Computable-POE.Rmd │ ├── Computable-POE.pdf │ ├── POE functions.R │ ├── POE-2021-05-MAY-DATA.xlsx │ ├── data │ │ ├── BOU_MMI_frontpage.rds │ │ └── POE-other-data.xlsx │ └── images │ │ ├── MDP.png │ │ ├── MOF_logo_600px_transparent_noborder.png │ │ └── Monitor.png ├── Dashboard Example.Rmd ├── HTML │ ├── csscheatsheet │ │ ├── css │ │ │ └── style.css │ │ └── images │ │ │ ├── bgimage.jpg │ │ │ └── check.png │ ├── example-website │ │ ├── css │ │ │ └── style.css │ │ └── images │ │ │ └── showcase.jpg │ └── htmlcheatsheet │ │ └── images │ │ └── sample.jpg ├── Latex │ ├── GentleLaTeXManual.pdf │ ├── LATEX for Beginners.pdf │ ├── Latex Paper Template │ │ ├── Example Paper - 2 Column Layout + References │ │ │ ├── bibliography.bib │ │ │ ├── israel and the syrian crisis.pdf │ │ │ └── israel and the syrian crisis.tex │ │ ├── Latex Paper Template.pdf │ │ ├── Latex Paper Template.tex │ │ └── Schools and Population Choropleth.pdf │ ├── Latex Presentation Template │ │ ├── Another Presentation │ │ │ ├── Dissertation Presentation.pdf │ │ │ └── Dissertation Presentation.tex │ │ ├── Example Presentation │ │ │ ├── Figures │ │ │ │ ├── Fig1.PNG │ │ │ │ ├── Fig2.PNG │ │ │ │ ├── Fig22.PNG │ │ │ │ ├── Fig3.PNG │ │ │ │ ├── Fig31.PNG │ │ │ │ ├── Fig33.PNG │ │ │ │ ├── Fig4.PNG │ │ │ │ ├── Fig41.PNG │ │ │ │ ├── Fig44.PNG │ │ │ │ ├── FigB12.PNG │ │ │ │ ├── FigB6.PNG │ │ │ │ ├── Site.PNG │ │ │ │ ├── Site2.PNG │ │ │ │ ├── Tab1.PNG │ │ │ │ ├── Tab11.PNG │ │ │ │ ├── Tab2.PNG │ │ │ │ ├── Tab3.PNG │ │ │ │ ├── Tab4.PNG │ │ │ │ └── Tab5.PNG │ │ │ ├── Lee, Miguel & Wolfram (2018).pdf │ │ │ └── Lee, Miguel & Wolfram (2018).tex │ │ ├── Latex Presentation Template (Beamer).pdf │ │ └── Latex Presentation Template (Beamer).tex │ ├── Not so Short Introduction to LATEX.pdf │ ├── a-quick-guide-to-latex.pdf │ ├── fiscal.pdf │ ├── fiscal.tex │ └── guide-tables.pdf ├── UGACAB.Rmd ├── Uganda-Covid.Rmd ├── Uganda-Covid.pdf ├── db.css ├── fiscal.Rmd └── fiscal.pdf ├── Course 7 - Web-Applications with Shiny in R ├── C7.R ├── Example Apps │ ├── app1 │ │ ├── app.R │ │ └── app_1_server.R │ ├── app2 │ │ ├── app.R │ │ └── www │ │ │ └── rstudio.png │ ├── app3 │ │ └── app.R │ ├── census-app │ │ ├── app.R │ │ ├── data │ │ │ └── counties.rds │ │ └── helpers.R │ ├── google-trend-index │ │ ├── app.R │ │ └── data │ │ │ ├── trend_data.csv │ │ │ └── trend_description.csv │ ├── lesson2 │ │ └── app.R │ ├── stockVis │ │ ├── app.R │ │ └── helpers.R │ ├── updateapp1 │ │ └── app.R │ ├── updateapp2 │ │ └── app.R │ ├── updateapp3 │ │ └── app.R │ ├── updatereactive-comparison │ │ ├── separated │ │ │ └── app.R │ │ └── together │ │ │ └── app.R │ ├── updatereactiveapp1 │ │ └── app.R │ ├── updatereactiveapp2 │ │ └── app.R │ └── updatereactiveoutput │ │ └── app.R ├── Full Apps │ ├── census-mapper │ │ ├── app.R │ │ ├── app_DATA.RData │ │ ├── census-mapper.Rproj │ │ ├── geoSERVER.R │ │ ├── geoUI.R │ │ └── styles.css │ └── shiny-data-portal │ │ ├── app.R │ │ ├── helpers.R │ │ ├── load_all.RData │ │ ├── server_code.R │ │ ├── shiny-data-portal.Rproj │ │ ├── style.css │ │ ├── ui_code.R │ │ └── www │ │ └── logo.png ├── outputs.png ├── shiny.pdf └── shiny.rstudio.com-tutorial │ ├── README.md │ ├── how-to-start-shiny-part-1.pdf │ ├── how-to-start-shiny-part-2.pdf │ ├── how-to-start-shiny-part-3.pdf │ ├── part-1-code │ ├── 01-template.R │ ├── 02-hist-app.R │ └── app.R │ ├── part-2-code │ ├── 01-two-inputs.R │ ├── 02-two-outputs.R │ ├── 03-reactive.R │ ├── 04-isolate.R │ ├── 05-actionButton.R │ ├── 06-observeEvent.R │ ├── 07-eventReactive.R │ └── 08-reactiveValues.R │ └── part-3-code │ ├── .DS_Store │ ├── 02-tags.R │ ├── 03-layout.R │ ├── 04-well.R │ ├── 05-tabs.R │ ├── 06-navlist.R │ ├── 07-sidebar.R │ ├── 08-navbarPage.R │ ├── 09-navbarMenu.R │ ├── App-Directory │ ├── .DS_Store │ ├── app.R │ └── www │ │ └── bigorb.png │ └── bootswatch-cerulean.css ├── Data Science Programme Flyer.jpg ├── Data-Science-Programme.Rproj ├── General Information and Further Resources └── Course Introduction Presentation │ ├── DS.PNG │ ├── General Information and Further Resources.Rmd │ ├── General-Information-and-Further-Resources.pdf │ ├── IMG_2155.PNG │ └── data-science.png ├── LICENSE ├── README.md └── Setup SSH Access on Github.R /.gitignore: -------------------------------------------------------------------------------- 1 | .Rproj.user 2 | .Rproj 3 | .Rhistory 4 | .RData 5 | .Ruserdata 6 | *.xls 7 | List*of*Participants.xlsx 8 | *.docx 9 | *.html 10 | *.db 11 | Adapted*R*Workshop/ 12 | Promotion/ 13 | *_files 14 | *_cache 15 | *.aux 16 | *.log 17 | *.out 18 | *.gz 19 | *.bak -------------------------------------------------------------------------------- /Course 1 - Basic Data Manipulation and Visualization in R/Archive/C1_S1_HW_more_EX.R: -------------------------------------------------------------------------------- 1 | readxl_web <- function(x, ...) { 2 | temp <- tempfile() 3 | download.file(x, temp, mode = "wb") 4 | on.exit(file.remove(temp)) 5 | readxl::read_excel(temp, ...) 6 | } 7 | 8 | BOU_I <- readxl_web("https://www.bou.or.ug/bou/bouwebsite/bouwebsitecontent/statistics/InterestRates/Interest_rates.xlsx", sheet = 2) 9 | 10 | # Problem 2: Accessing data from an API package ---------------------------------------- 11 | library(wbstats) 12 | library(tradestatistics) 13 | # Download the following API packages and get some interesting development and trade related data using them. 14 | 15 | # Using the R data viewer, find out which was the most exported and imported product of Uganda in 2018 16 | 17 | # Problem 3: Analyzing Macroeconomic Data from BoU ------------------------------------- 18 | 19 | # Using the readxl_web function above, import the Monthly macroeconomic indicators dataset from the Bank of Uganda 20 | # Tipp: You want to first download the file manually, then 21 | 22 | # Create a plot... 23 | 24 | # Problem 4: Learning R Using Swirl ---------------------------------------------------- 25 | -------------------------------------------------------------------------------- /Course 1 - Basic Data Manipulation and Visualization in R/Archive/Macro-Data-Portal Excercise.R: -------------------------------------------------------------------------------- 1 | 2 | # Problem 3: Basic Statistical Analysis using the Macro Data Portal -------------------------- 3 | # Open a browser and go to the Macro Data Portal Website: https://mepd.shinyapps.io/Macro-Data-Portal/ 4 | # The dataset shown is the total fiscal operations, Updated to October 2020 5 | # Click on the 'Variables' tab, and examine the variables. This should look familiar to you from the GFS excel sheet. 6 | # Look at the 'Class' column. Do you recognize the R type and in brackets behind the storage type of the variables? 7 | 8 | # Now on your left where is says 'Select Variables', select all the time variables (Date-Month) 9 | # and additionally the variables 'REV_TOT', 'REV_URA', 'REV_NON_URA', 'GRA_TOT'. Click 'Apply Selection' 10 | # Go to the 'Summary' tab and briefly examine the statistics of the data. 11 | # Now go to the plot window. What do you notice? Can you see the impact of COVID-19? 12 | # On the top left you can click, on 'Joint' to see all series in one chart, then go back to 'Individual Series'. 13 | # We will look at this a bit more closely. Go back to the 'Table' tab and hit the 'Filter Data' checkbox. 14 | # Click on the blue question mark and briefly comprehend the message. 15 | # Now you will only consider data since 2017. Type 'Year >= 2017' in the filter query box and hit 'Apply Filter'. 16 | # Go back to the 'Plot' tab. You should now only see data from 2017 in the plot. 17 | # To more clearly see the impact of COVID-19 on revenue, we will get rid of some seasonality in the plot. 18 | # On your left there is a checkbox called 'Transform Data'. Hit that checkbox. 19 | # In the field 'Data Transformations' scroll down until you find a filter called 'cubic spline trend (very soft)'. 20 | # At the bottom hit the checkbox 'Add Transformed Variables' and click the 'Transform' button. 21 | # You should now see two lines in each chart, the original series in red and a smooth trend in green. 22 | # The trend can give you an idea of what the impact of COVID-19 on revenue could have been. 23 | # Now we will use this trend to seasonally adjust the data. Therefore click on 'cubic spline trend (very soft)' 24 | # and remove it by hitting delete or backspace on your keyboard. Now scroll down all the way to the bottom of the 25 | # list of filters and hit 'Seasonal adj. on cubic spline (very soft)'. 26 | # What this will do is subtract the smooth trend from the data, then regress the residuals on a series of monthly dummy 27 | # variables, and add the residuals from the regression back to the smooth trend. 28 | # Examine this seasonally adjusted data: In which month was the greatest impact on URA revenue? (you may want to use the 'Table' tab to also look at the numbers.) 29 | 30 | # Finally, we will aggregate this data to quarterly frequency and look at this again. 31 | # To do this, first go back to the 'Table' tab. This data runs up to October 2020, which is part of the new quarter. 32 | # Let's remove this value by changing the filter query to 'Year >= 2017 & Date < "2020-10-01"'. 33 | # Now further down hit the 'Aggregate' checkbox. Select 'Year' and 'Quarter' (or alternatively 'FY' and 'QFY') as aggregator ID variables 34 | # In the 'Aggregator Functions' box, remove the mean and select the sum. Then hit 'Aggregate'. 35 | # Go back to the 'Plot' window. In which Quarter of 2020 was the greatest revenue shortfall?. 36 | 37 | # Finally, you will download this data and open it in R. Go back to the 'Table' tab and at the bottom left of the page hit 38 | # 'R' and then download. Your browser should then bring up a window where you can save of choose to open the file. 39 | # Click on 'Open with', and then search for 'Rstudio' as the program to open the file and hit OK. 40 | # Rstudio should now open and you will be requested to give a name to the dataset, the default being 'Overall Fiscal Operations'. 41 | # Change this to 'REV' and hit OK. You should now see the 'REV' dataset in your global environment, along with 42 | # a line of code printed in the console that imported your data. Click on 'REV' in the global environment to view the data in Rstudio. 43 | # summarize the dat aby typing summary(REV) into the console. 44 | 45 | # That's it, you survived the first session and homework assignment. We will be taking off from here and doing some analysis 46 | # ourself in R after the next session. 47 | 48 | 49 | 50 | -------------------------------------------------------------------------------- /Course 1 - Basic Data Manipulation and Visualization in R/BaseGraphicsCheatsheet.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SebKrantz/Data-Science-Programme/1f0ea0ea50a940f950b09e684e610aa684756ac6/Course 1 - Basic Data Manipulation and Visualization in R/BaseGraphicsCheatsheet.pdf -------------------------------------------------------------------------------- /Course 1 - Basic Data Manipulation and Visualization in R/C1_S1_HW.R: -------------------------------------------------------------------------------- 1 | ############################################ 2 | # Data Science Training 3 | # Homework Assignment of Course 1 Session 1 4 | ############################################ 5 | 6 | # Problem 1: Basic Statistical Programming ------------------- 7 | # consider the following vector of random numbers drawn from a 8 | # normal distribution with mean 10 and standard deviation 2 9 | x <- rnorm(100, mean = 10, sd = 2) 10 | 11 | # (a) plot a histogram of x using hist() 12 | 13 | # (b) compute the sum, mean, median, standard deviation, minimum and maximum values and quantiles of this vector 14 | 15 | # (c) manually compute the mean using sum() and length() 16 | 17 | # (d) check your computation of the mean, median, minimum, maximum, 2nd and 4th quartile against: 18 | summary(x) 19 | 20 | # (e) write a function that takes x as an input and returns the same output as summary(x) 21 | 22 | # (f) This inserts 10 missing values at random into x. 23 | x[sample.int(100L, 10L)] <- NA 24 | x 25 | ?sample.int # See the help page of this function, make sure you understand the code above 26 | 27 | summary(x) # see the output now 28 | 29 | # (g) Modify your function in part (e) to also replicate this output 30 | 31 | # (h) Add an argument 'na.rm' to your function, and modify your function so that it can produce both outputs of (e) and (g) depending on na.rm = TRUE or FALSE 32 | 33 | # (i) Consider this dataset that comes with R 34 | mtcars 35 | View(mtcars) 36 | # make sure you understand this code. Look up the individual functions i.e. ?t, ?sapply 37 | summ <- t(sapply(mtcars, summary)) 38 | summ 39 | # Examine 'summ'. What kind of object is it?, see the structure and class of it 40 | 41 | # (j) apply your function to each column of the data in the same way as shown above. Do you get the same result? 42 | 43 | # (k) using the matrix() and sample.int() functions, insert missing values into mtcars and repeat. 44 | 45 | # (l) Consider the iris dataset printed below. Create a generic version of your function in part (h), 46 | # adding a default method that that tabulates non-numeric data and apply it to the columns of iris using lapply(). 47 | head(iris) 48 | str(iris) 49 | summary(iris) 50 | 51 | 52 | # Problem 2: Strings and Dates ----------------------------------- 53 | # consider the following vector of fiscal years 54 | y <- 1999:2017 55 | fy <- paste(y - 1L, substr(as.character(y), 3L, 4L), sep = "/") 56 | 57 | # (a) make sure you understand how these fiscal year strings were generated by looking up the relevant functions, e.g. ?substr 58 | 59 | # (b) wrap this code into a function called FY(), that can create sequences of fiscal years from arbitrary starting and ending calendar years 60 | 61 | # (c) now create a function FY_to_Date() that takes a vector of fiscal years and converts it to a vector of Dates corresponding to the last day (30th of June) of each fiscal year 62 | 63 | # (d) generate a vector of fiscal years and apply your function to turn them into dates. 64 | 65 | # (e) using substr(), get the month from these generated dates. 66 | 67 | -------------------------------------------------------------------------------- /Course 1 - Basic Data Manipulation and Visualization in R/C1_S1_HW_SOL.R: -------------------------------------------------------------------------------- 1 | ############################################ 2 | # Data Science Training 3 | # Homework Assignment of Course 1 Session 1 4 | # Solution 5 | ############################################ 6 | 7 | # Problem 1: Basic Statistical Programming ------------------- 8 | # consider the following vector of random numbers drawn from a 9 | # normal distribution with mean 10 and standard deviation 2 10 | x <- rnorm(100, mean = 10, sd = 2) 11 | 12 | # (a) plot a histogram of x using hist() 13 | hist(x) 14 | 15 | # (b) compute the sum, mean, median, standard deviation, minimum and maximum values and quantiles of this vector 16 | sum(x) 17 | mean(x) 18 | median(x) 19 | sd(x) 20 | min(x) 21 | max(x) 22 | quantile(x) 23 | 24 | # (c) manually compute the mean using sum() and length() 25 | sum(x) / length(x) 26 | 27 | # (d) check your computation of the mean, median, minimum, maximum, 2nd and 4th quartile against: 28 | summary(x) 29 | 30 | # (e) write a function that takes x as an input and returns the same output as summary(x) 31 | my_summary <- function(x) c(`Min.` = min(x), `1st Qu.` = unname(quantile(x, 0.25)), 32 | Median = median(x), Mean = mean(x), `3rd Qu.` = unname(quantile(x, 0.75)), 33 | `Max.` = max(x)) 34 | my_summary(x) 35 | 36 | # (f) This inserts 10 missing values at random into x. 37 | x[sample.int(100L, 10L)] <- NA 38 | x 39 | ?sample.int # See the help page of this function, make sure you understand the code above 40 | 41 | summary(x) # see the output now 42 | 43 | # (g) Modify your function in part (e) to also replicate this output 44 | my_summary <- function(x) c(`Min.` = min(x, na.rm = TRUE), 45 | `1st Qu.` = unname(quantile(x, 0.25, na.rm = TRUE)), 46 | Median = median(x, na.rm = TRUE), 47 | Mean = mean(x, na.rm = TRUE), 48 | `3rd Qu.` = unname(quantile(x, 0.75, na.rm = TRUE)), 49 | `Max.` = max(x, na.rm = TRUE), 50 | `NA's` = sum(is.na(x))) 51 | my_summary(x) 52 | 53 | # (h) Add an argument 'na.rm' to your function, and modify your function so that it can produce both outputs of (e) and (g) depending on na.rm = TRUE or FALSE 54 | my_summary <- function(x, na.rm = FALSE) { 55 | if(na.rm) nas = c(`NA's` = sum(is.na(x))) 56 | c(`Min.` = min(x, na.rm = na.rm), 57 | `1st Qu.` = unname(quantile(x, 0.25, na.rm = na.rm)), 58 | Median = median(x, na.rm = na.rm), 59 | Mean = mean(x, na.rm = na.rm), 60 | `3rd Qu.` = unname(quantile(x, 0.75, na.rm = na.rm)), 61 | `Max.` = max(x, na.rm = na.rm), if(na.rm) nas) 62 | } 63 | 64 | my_summary(rnorm(100, mean = 10, sd = 2)) 65 | my_summary(x, na.rm = TRUE) 66 | 67 | # (i) Consider this dataset that comes with R 68 | mtcars 69 | View(mtcars) 70 | 71 | # make sure you understand this code. Look up the individual functions i.e. ?t, ?sapply 72 | summ <- t(sapply(mtcars, summary)) 73 | summ 74 | 75 | # Examine 'summ'. What kind of object is it?, see the structure and class of it 76 | str(summ) 77 | class(summ) 78 | 79 | # (j) apply your function to each column of the data in the same way as shown above. Do you get the same result? 80 | t(sapply(mtcars, my_summary)) 81 | summ 82 | 83 | all.equal(t(sapply(mtcars, my_summary)), summ) 84 | 85 | # (k) using the matrix() and sample.int() functions, insert missing values into mtcars and repeat. 86 | mat <- matrix(TRUE, nrow = nrow(mtcars), ncol = ncol(mtcars)) 87 | # Here setting 30 values to missing at random 88 | mat[sample.int(length(mat), 30L)] <- FALSE 89 | mat 90 | mtcars[mat] <- NA 91 | 92 | t(sapply(mtcars, summary, na.rm = TRUE)) 93 | t(sapply(mtcars, my_summary, na.rm = TRUE)) 94 | 95 | # (l) Consider the iris dataset printed below. Create a generic version of your function in part (h), 96 | # adding a default method that that tabulates non-numeric data and apply it to the columns of iris using lapply(). 97 | head(iris) 98 | str(iris) 99 | summary(iris) 100 | 101 | # Generic version of the function 102 | my_summary <- function(x, na.rm = FALSE) UseMethod("my_summary") 103 | 104 | # The function we had before becomes the method for numeric data 105 | my_summary.numeric <- function(x, na.rm = FALSE) { 106 | if(na.rm) nas = c(`NA's` = sum(is.na(x))) 107 | c(`Min.` = min(x, na.rm = na.rm), 108 | `1st Qu.` = unname(quantile(x, 0.25, na.rm = na.rm)), 109 | Median = median(x, na.rm = na.rm), 110 | Mean = mean(x, na.rm = na.rm), 111 | `3rd Qu.` = unname(quantile(x, 0.75, na.rm = na.rm)), 112 | `Max.` = max(x, na.rm = na.rm), if(na.rm) nas) 113 | } 114 | 115 | # The default method applied to all other data 116 | my_summary.default <- function(x, na.rm = FALSE) { 117 | if(na.rm) nas = c(`NA's` = sum(is.na(x))) 118 | c(table(x), if(na.rm) nas) 119 | } 120 | 121 | # Applying the function to the columns in the dataset 122 | lapply(iris, my_summary) 123 | 124 | # Compare this to the output of summary: 125 | summary(iris) 126 | 127 | # Note: These are possible alternative definitions of the generic function 128 | my_summary <- function(x, ...) UseMethod("my_summary") 129 | my_summary <- function(x, na.rm = FALSE) UseMethod("my_summary", x) 130 | # The first allows a variable number of arguments to be passed to different methods (not applicable here), 131 | # and the second just makes it explicit that we want methods will be chosen based on the type of the 'x' argument, 132 | # which is also not necessary here as UseMethod() dispatches on the first function argument by default. 133 | 134 | 135 | 136 | 137 | # Problem 2: Strings and Dates ----------------------------------- 138 | # consider the following vector of fiscal years 139 | y <- 1999:2017 140 | fy <- paste(y - 1L, substr(as.character(y), 3L, 4L), sep = "/") 141 | 142 | # (a) make sure you understand how these fiscal year strings were generated by looking up the relevant functions, e.g. ?substr 143 | ?substr 144 | 145 | # (b) wrap this code into a function called FY(), that can create sequences of fiscal years from arbitrary starting and ending calendar years 146 | FY <- function(start, end) { 147 | y <- start:end 148 | paste(y - 1L, substr(as.character(y), 3L, 4L), sep = "/") 149 | } 150 | 151 | FY(1999, 2017) 152 | FY(2001, 2020) 153 | 154 | # (c) now create a function FY_to_Date() that takes a vector of fiscal years and converts it to a vector of Dates corresponding to the last day (30th of June) of each fiscal year 155 | FY_to_Date <- function(fy) as.Date(paste0(as.integer(substr(fy, 1L, 4L)) + 1L, "-06-30")) 156 | FY_to_Date(fy) 157 | 158 | # (d) generate a vector of fiscal years and apply your function to turn them into dates. 159 | dates <- FY_to_Date(FY(2001, 2020)) 160 | 161 | # (e) using substr(), get the month from these generated dates. 162 | as.integer(substr(dates, 6L, 7L)) 163 | 164 | -------------------------------------------------------------------------------- /Course 1 - Basic Data Manipulation and Visualization in R/C1_S2_ICE_SOL.R: -------------------------------------------------------------------------------- 1 | ############################################ 2 | # Data Science Training 3 | # Solution to the In-Class Exercises of 4 | # Course 1 Session 2 5 | ############################################ 6 | 7 | #**************************** 8 | ### In-Class Exercise 1 ----- 9 | #**************************** 10 | 11 | # (a) Consider the following two objects. Compute the sum along the columns of these objects in the most efficient way so that the result is a vector 12 | state.x77 13 | longley 14 | 15 | str(state.x77) # This is a matrix 16 | str(longley) # This is a data.frame 17 | 18 | colSums(state.x77) # Most efficient matrix column sums: Using colSums() 19 | vapply(longley, sum, numeric(1L)) # Most efficient data.frame column sums: Using vapply(), where we also need to declare that the result for each column will be a numeric vector of lenth 1. 20 | 21 | # (b) Show an alternative way of summing along the columns of these objects, again resulting in a vector. 22 | apply(state.x77, 2L, sum) # apply() supports any function but is substantially slower than colSums() 23 | sapply(longley, sum) # sapply() applies a function to each column in a data.frame and simplifies the result. 24 | # It needs to perform some checks to figre out how to simplify things, so it is slower than vapply() where we declare what the result will be. 25 | 26 | # (c) Consider the titanic data. Compute the percent that survived by Sex and Age 27 | Titanic 28 | str(Titanic) # 4D array 29 | ag_class <- apply(Titanic, 2:4, sum) # First we sum over class 30 | ag_class[,,"Yes"] / apply(ag_class, 1:2, sum) * 100 # Then divide survived matrix by total matrix, multiply by 100 to get percentages 31 | 32 | # (d) Consider these two datasets. Aggregate 'infert' by education and induced, and 'airquality' by Month 33 | infert 34 | aggregate(infert[-c(1L, 4L)], by = infert[c(1L, 4L)], FUN = mean) 35 | airquality 36 | aggregate(airquality[-5L], by = airquality[5L], FUN = mean, na.rm = TRUE) # Ned to add na.rm = TRUE here as columns Ozone and Solar.R have missing values. 37 | 38 | # (e) Using the iris dataset, compute the quantiles of Sepal.Width by Species and simplify the result to a matrix. 39 | iris 40 | do.call(rbind, tapply(iris$Sepal.Width, iris$Species, quantile)) # Can use simplify2array(...) instead of do.call(rbind, ...), but the latter is more efficient. 41 | 42 | 43 | #**************************** 44 | ### In-Class Exercise 2 ----- 45 | #**************************** 46 | 47 | # (a) Go to the CRAN Task Views and look for interesting packages in a task view 48 | 49 | # CRAN Task Views are available online at: https://cran.r-project.org/web/views/ 50 | 51 | # (b) Using RWsearch, search for packages in the field you find most interesting 52 | 53 | 54 | #**************************** 55 | ### In-Class Exercise 3 ----- 56 | #**************************** 57 | 58 | # (a) Find the introduction to 'data.table' vignette and the introduction to 'xts' vignette. 59 | vignette("datatable-intro") 60 | vignette("xts") 61 | 62 | # (b) Install the packages 'magrittr', 'matrixStats' and 'ggplot2' and find the vignettes 63 | install.packages(c("magrittr", "matrixStats", "ggplot2")) 64 | vignette("magrittr") 65 | vignette("matrixStats-methods") 66 | browseVignettes("ggplot2") 67 | 68 | # (c) Find the website for 'collapse', access the introductory vignette 69 | # and look for the section on advanced data aggregation 70 | # Website: https://sebkrantz.github.io/collapse/index.html 71 | # Section on Advanced Data Aggregation: https://sebkrantz.github.io/collapse/articles/collapse_intro.html#5-advanced-data-aggregation 72 | 73 | # (d) Find the cheatsheets for 'collapse', 'data.table' and 'ggplot2' on the Rstudio website. 74 | # Can be downloaded from here: https://rstudio.com/resources/cheatsheets/ 75 | 76 | # (e) Execute all examples given for the 'lm' function 77 | example("lm") 78 | 79 | 80 | #**************************** 81 | ### In-Class Exercise 4 ----- 82 | #**************************** 83 | 84 | # Using the haven library, import the STATA File "sachs 2003 institutions don't rule.dta". 85 | data <- haven::read_dta("data/sachs 2003 institutions don't rule.dta") 86 | 87 | # (a) Summarise the data 88 | summary(data) 89 | 90 | # (b) Delete the columns 'AJR' and 'ME' from the data 91 | data[c("AJR", "ME")] <- NULL 92 | 93 | # (c) Save the file as a STATA 10 file in the 'data' folder. 94 | haven::write_dta(data, "data/sachs_STATA10.dta", version = 10) 95 | 96 | # (d) Save the file as an Excel file in the 'data' folder. 97 | writexl::write_xlsx(list(data = data, namlab = collapse::namlab(data)), 98 | "data/sachs.xlsx") # Passing a list of data.frame's to write_xlsx() creates an excel workbook with multiple sheets. 99 | 100 | # (e) Save the file as a CSV file in the 'data' folder. 101 | readr::write_csv(data, "data/sachs.csv") 102 | 103 | 104 | #**************************** 105 | ### In-Class Exercise 5 ----- 106 | #**************************** 107 | 108 | # Using the iris dataset, do the following: 109 | iris 110 | 111 | # (a) Create a side-by-side plot array of the histogram and density of Sepal.Length 112 | par(mfrow = c(1, 2)) 113 | hist(iris$Sepal.Length) 114 | plot(density(iris$Sepal.Length)) 115 | par(mfrow = c(1, 1)) # Need to undo this for the next 116 | 117 | # (a) Create a scatterplot matrix of the data using the pairs() function 118 | pairs(iris) 119 | 120 | # (b) Create a correlation plot of the numeric variables in the data using the corrplot() function 121 | corrplot(cor(iris[1:4]), method = "ellipse") 122 | 123 | # (c) Create a scatter plot of Sepal.Length against Sepal.Width, coloured by Species. 124 | plot(Sepal.Length ~ Sepal.Width, data = iris, col = iris$Species, pch = 16) # Using point shape 16 giving filled dots 125 | # (Optionally) adding a legend. 126 | legend("topleft", legend = levels(iris$Species), 127 | col = unique(iris$Species), pch = 16) 128 | 129 | # (d) Add a regression line using abline() 130 | abline(lm(Sepal.Length ~ Sepal.Width, data = iris)) 131 | 132 | # (e) Add a blue coloured smooth trend line using lines() and the supsmu() function. 133 | trend <- supsmu(iris$Sepal.Width, 134 | iris$Sepal.Length, bass = 10) 135 | # Add this trend curve to the plot 136 | lines(trend, col = "blue") 137 | 138 | # (f) Create a boxplot of Sepal.Length by Species 139 | boxplot(Sepal.Length ~ Species, data = iris) 140 | 141 | # (g) Compute the average Sepal.Length by species and create a barchart. 142 | barplot(tapply(iris$Sepal.Length, iris$Species, mean)) 143 | -------------------------------------------------------------------------------- /Course 1 - Basic Data Manipulation and Visualization in R/base-r.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SebKrantz/Data-Science-Programme/1f0ea0ea50a940f950b09e684e610aa684756ac6/Course 1 - Basic Data Manipulation and Visualization in R/base-r.pdf -------------------------------------------------------------------------------- /Course 1 - Basic Data Manipulation and Visualization in R/data/Amount_of_Water_Supplied_and_Billing_efficiency_by_NWSC.csv: -------------------------------------------------------------------------------- 1 | Town,H2O Produced (m3) 2016/17,H2O Supplied (m3) 2016/17,H2O Sold (m3) 2016/17,Billing Efficiency () 2 | Kampala Metropolitan,"77,200,804","76,217,631","47,667,664",62.5 3 | Jinja,"6,912,557","5,562,915","4,278,174",76.9 4 | Entebbe/Kajansi,"6,381,783","5,959,683","4,963,718",83.3 5 | Tororo,"1,019,285","1,019,285","914,292",89.7 6 | Mbale,"2,292,870","2,267,064","1,985,716",87.6 7 | Mbarara,"4,731,568","4,433,840","3,330,563",75.1 8 | Masaka,"2,500,388","2,206,433","1,750,658",79.3 9 | Lira,"2,073,465","1,948,581","1,437,172",73.8 10 | Gulu,"1,104,049","1,004,204","869,166",86.6 11 | Moroto,"153,151","153,151","130,704",85.3 12 | Kasese,"1,131,140","1,102,512","888,080",80.6 13 | FortPortal,"1,117,003","1,063,847","897,502",84.4 14 | Kabale,"714,997","676,920","578,805",85.5 15 | Arua,"1,209,677","950,974","739,903",77.8 16 | Bushenyi/ Ishaka,"1,210,764","1,107,639","863,367",77.9 17 | Soroti,"1,064,690","1,056,487","914,258",86.5 18 | Busia,"303,489","297,110","258,339",87 19 | Kapchorwa,"143,228","128,568","70,023",54.5 20 | Hoima,"622,085","519,405","419,178",80.7 21 | Masindi,"729,434","678,436","563,218",83 22 | Mubende,"606,292","586,401","544,412",92.8 23 | Lugazi,"404,509","404,297","303,996",75.2 24 | Iganga,"248,557","1,096,314","813,528",74.2 25 | Kisoro,"476,903","440,910","310,068",70.3 26 | Kitgum,"307,137","254,506","231,676",91 27 | Mityana,"423,362","403,226","335,190",83.1 28 | Kamuli/Mbulimuti,"182,867","170,353","136,178",79.9 29 | Mpigi,"312,621","265,170","173,085",65.3 30 | Pader,"183,111","171,003","124,671",72.9 31 | Apac/Aduku,"138,026","138,026","117,445",85.1 32 | Luweero,"681,540","681,540","587,770",86.2 33 | Wobulenzi,,-,, 34 | Kabwohe/Itendero,,-,, 35 | Kalisizo,,-,, 36 | Rukungiri,"248,158","246,641","189,615",76.9 37 | Kanungu,"266,193","266,193","219,989",82.6 38 | Kitagata,,-,, 39 | Bweyale/Kiryandongo,"154,292","156,796","128,142",81.7 40 | Kaliro,,-,, 41 | Kamwenge,"186,782","180,677","146,659",81.2 42 | Adjumani,"165,980","165,566","143,580",86.7 43 | Rushere,"108,041","107,543","93,556",87 44 | Ntungamo,"389,731","327,269","258,229",78.9 45 | Ruhama,"134,999","134,999","102,078",75.6 46 | Kigumba,"121,930","121,800","108,239",88.9 47 | Lyantonde,"373,010","225,627","184,219",81.6 48 | Bombo,,-,, 49 | Mpondwe,"401,032","351,857","275,610",78.3 50 | Kyotera,"500,588","460,789","390,096",84.7 51 | Nebbi/Paidha,"605,534","518,870","431,748",83.2 52 | Ibanda,"354,626","323,024","282,230",87.4 53 | Total ,"120,592,248","116,554,081","80,152,502",68.8 54 | -------------------------------------------------------------------------------- /Course 1 - Basic Data Manipulation and Visualization in R/data/Pupil_Teacher_Ratio_by_District.xlsx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SebKrantz/Data-Science-Programme/1f0ea0ea50a940f950b09e684e610aa684756ac6/Course 1 - Basic Data Manipulation and Visualization in R/data/Pupil_Teacher_Ratio_by_District.xlsx -------------------------------------------------------------------------------- /Course 1 - Basic Data Manipulation and Visualization in R/data/sachs 2003 institutions don't rule.dta: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SebKrantz/Data-Science-Programme/1f0ea0ea50a940f950b09e684e610aa684756ac6/Course 1 - Basic Data Manipulation and Visualization in R/data/sachs 2003 institutions don't rule.dta -------------------------------------------------------------------------------- /Course 1 - Basic Data Manipulation and Visualization in R/figures/ptr_district_dotchart.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SebKrantz/Data-Science-Programme/1f0ea0ea50a940f950b09e684e610aa684756ac6/Course 1 - Basic Data Manipulation and Visualization in R/figures/ptr_district_dotchart.pdf -------------------------------------------------------------------------------- /Course 1 - Basic Data Manipulation and Visualization in R/figures/ptr_year_barplot.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SebKrantz/Data-Science-Programme/1f0ea0ea50a940f950b09e684e610aa684756ac6/Course 1 - Basic Data Manipulation and Visualization in R/figures/ptr_year_barplot.pdf -------------------------------------------------------------------------------- /Course 1 - Basic Data Manipulation and Visualization in R/figures/superheat.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SebKrantz/Data-Science-Programme/1f0ea0ea50a940f950b09e684e610aa684756ac6/Course 1 - Basic Data Manipulation and Visualization in R/figures/superheat.pdf -------------------------------------------------------------------------------- /Course 2 - Advanced Data Manipulation and Visualization in R/cheatsheets/collapse.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SebKrantz/Data-Science-Programme/1f0ea0ea50a940f950b09e684e610aa684756ac6/Course 2 - Advanced Data Manipulation and Visualization in R/cheatsheets/collapse.pdf -------------------------------------------------------------------------------- /Course 2 - Advanced Data Manipulation and Visualization in R/cheatsheets/datatable.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SebKrantz/Data-Science-Programme/1f0ea0ea50a940f950b09e684e610aa684756ac6/Course 2 - Advanced Data Manipulation and Visualization in R/cheatsheets/datatable.pdf -------------------------------------------------------------------------------- /Course 2 - Advanced Data Manipulation and Visualization in R/cheatsheets/ggplot2.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SebKrantz/Data-Science-Programme/1f0ea0ea50a940f950b09e684e610aa684756ac6/Course 2 - Advanced Data Manipulation and Visualization in R/cheatsheets/ggplot2.pdf -------------------------------------------------------------------------------- /Course 2 - Advanced Data Manipulation and Visualization in R/data/Ag_SAM_modified.xlsx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SebKrantz/Data-Science-Programme/1f0ea0ea50a940f950b09e684e610aa684756ac6/Course 2 - Advanced Data Manipulation and Visualization in R/data/Ag_SAM_modified.xlsx -------------------------------------------------------------------------------- /Course 2 - Advanced Data Manipulation and Visualization in R/data/BOU_MMI.xlsx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SebKrantz/Data-Science-Programme/1f0ea0ea50a940f950b09e684e610aa684756ac6/Course 2 - Advanced Data Manipulation and Visualization in R/data/BOU_MMI.xlsx -------------------------------------------------------------------------------- /Course 2 - Advanced Data Manipulation and Visualization in R/data/BOU_MMI_labels.xlsx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SebKrantz/Data-Science-Programme/1f0ea0ea50a940f950b09e684e610aa684756ac6/Course 2 - Advanced Data Manipulation and Visualization in R/data/BOU_MMI_labels.xlsx -------------------------------------------------------------------------------- /Course 2 - Advanced Data Manipulation and Visualization in R/data/UBOS 2014 Census.rds: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SebKrantz/Data-Science-Programme/1f0ea0ea50a940f950b09e684e610aa684756ac6/Course 2 - Advanced Data Manipulation and Visualization in R/data/UBOS 2014 Census.rds -------------------------------------------------------------------------------- /Course 2 - Advanced Data Manipulation and Visualization in R/data/UNHS_pov16.dta: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SebKrantz/Data-Science-Programme/1f0ea0ea50a940f950b09e684e610aa684756ac6/Course 2 - Advanced Data Manipulation and Visualization in R/data/UNHS_pov16.dta -------------------------------------------------------------------------------- /Course 2 - Advanced Data Manipulation and Visualization in R/data/plotdata/2 Extra attainment indicators from WDI.dta: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SebKrantz/Data-Science-Programme/1f0ea0ea50a940f950b09e684e610aa684756ac6/Course 2 - Advanced Data Manipulation and Visualization in R/data/plotdata/2 Extra attainment indicators from WDI.dta -------------------------------------------------------------------------------- /Course 2 - Advanced Data Manipulation and Visualization in R/data/plotdata/Data_Extract_From_Education_Statistics_-_All_Indicators.xlsx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SebKrantz/Data-Science-Programme/1f0ea0ea50a940f950b09e684e610aa684756ac6/Course 2 - Advanced Data Manipulation and Visualization in R/data/plotdata/Data_Extract_From_Education_Statistics_-_All_Indicators.xlsx -------------------------------------------------------------------------------- /Course 2 - Advanced Data Manipulation and Visualization in R/data/plotdata/Governance, Uganda + Regional Aggregates, 2010-2016 Average.dta: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SebKrantz/Data-Science-Programme/1f0ea0ea50a940f950b09e684e610aa684756ac6/Course 2 - Advanced Data Manipulation and Visualization in R/data/plotdata/Governance, Uganda + Regional Aggregates, 2010-2016 Average.dta -------------------------------------------------------------------------------- /Course 2 - Advanced Data Manipulation and Visualization in R/data/plotdata/HDI Trends.dta: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SebKrantz/Data-Science-Programme/1f0ea0ea50a940f950b09e684e610aa684756ac6/Course 2 - Advanced Data Manipulation and Visualization in R/data/plotdata/HDI Trends.dta -------------------------------------------------------------------------------- /Course 2 - Advanced Data Manipulation and Visualization in R/data/plotdata/Schools.xlsx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SebKrantz/Data-Science-Programme/1f0ea0ea50a940f950b09e684e610aa684756ac6/Course 2 - Advanced Data Manipulation and Visualization in R/data/plotdata/Schools.xlsx -------------------------------------------------------------------------------- /Course 2 - Advanced Data Manipulation and Visualization in R/data/plotdata/Uganda Districts Shapefile/Districts_2014_UBOS.cpg: -------------------------------------------------------------------------------- 1 | UTF-8 -------------------------------------------------------------------------------- /Course 2 - Advanced Data Manipulation and Visualization in R/data/plotdata/Uganda Districts Shapefile/Districts_2014_UBOS.dbf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SebKrantz/Data-Science-Programme/1f0ea0ea50a940f950b09e684e610aa684756ac6/Course 2 - Advanced Data Manipulation and Visualization in R/data/plotdata/Uganda Districts Shapefile/Districts_2014_UBOS.dbf -------------------------------------------------------------------------------- /Course 2 - Advanced Data Manipulation and Visualization in R/data/plotdata/Uganda Districts Shapefile/Districts_2014_UBOS.prj: -------------------------------------------------------------------------------- 1 | PROJCS["Arc_1960_UTM_Zone_36N",GEOGCS["GCS_Arc_1960",DATUM["D_Arc_1960",SPHEROID["Clarke_1880_RGS",6378249.145,293.465]],PRIMEM["Greenwich",0.0],UNIT["Degree",0.0174532925199433]],PROJECTION["Transverse_Mercator"],PARAMETER["False_Easting",500000.0],PARAMETER["False_Northing",0.0],PARAMETER["Central_Meridian",33.0],PARAMETER["Scale_Factor",0.9996],PARAMETER["Latitude_Of_Origin",0.0],UNIT["Meter",1.0]] -------------------------------------------------------------------------------- /Course 2 - Advanced Data Manipulation and Visualization in R/data/plotdata/Uganda Districts Shapefile/Districts_2014_UBOS.shp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SebKrantz/Data-Science-Programme/1f0ea0ea50a940f950b09e684e610aa684756ac6/Course 2 - Advanced Data Manipulation and Visualization in R/data/plotdata/Uganda Districts Shapefile/Districts_2014_UBOS.shp -------------------------------------------------------------------------------- /Course 2 - Advanced Data Manipulation and Visualization in R/data/plotdata/Uganda Districts Shapefile/Districts_2014_UBOS.shx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SebKrantz/Data-Science-Programme/1f0ea0ea50a940f950b09e684e610aa684756ac6/Course 2 - Advanced Data Manipulation and Visualization in R/data/plotdata/Uganda Districts Shapefile/Districts_2014_UBOS.shx -------------------------------------------------------------------------------- /Course 2 - Advanced Data Manipulation and Visualization in R/figures/HDI Trends.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SebKrantz/Data-Science-Programme/1f0ea0ea50a940f950b09e684e610aa684756ac6/Course 2 - Advanced Data Manipulation and Visualization in R/figures/HDI Trends.pdf -------------------------------------------------------------------------------- /Course 2 - Advanced Data Manipulation and Visualization in R/figures/R colors.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SebKrantz/Data-Science-Programme/1f0ea0ea50a940f950b09e684e610aa684756ac6/Course 2 - Advanced Data Manipulation and Visualization in R/figures/R colors.pdf -------------------------------------------------------------------------------- /Course 2 - Advanced Data Manipulation and Visualization in R/figures/Schools and Population Choropleth.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SebKrantz/Data-Science-Programme/1f0ea0ea50a940f950b09e684e610aa684756ac6/Course 2 - Advanced Data Manipulation and Visualization in R/figures/Schools and Population Choropleth.pdf -------------------------------------------------------------------------------- /Course 2 - Advanced Data Manipulation and Visualization in R/figures/Schools by Size Map FINAL.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SebKrantz/Data-Science-Programme/1f0ea0ea50a940f950b09e684e610aa684756ac6/Course 2 - Advanced Data Manipulation and Visualization in R/figures/Schools by Size Map FINAL.pdf -------------------------------------------------------------------------------- /Course 2 - Advanced Data Manipulation and Visualization in R/figures/Schools by Size Map.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SebKrantz/Data-Science-Programme/1f0ea0ea50a940f950b09e684e610aa684756ac6/Course 2 - Advanced Data Manipulation and Visualization in R/figures/Schools by Size Map.pdf -------------------------------------------------------------------------------- /Course 2 - Advanced Data Manipulation and Visualization in R/figures/Uganda Education Trends 1.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SebKrantz/Data-Science-Programme/1f0ea0ea50a940f950b09e684e610aa684756ac6/Course 2 - Advanced Data Manipulation and Visualization in R/figures/Uganda Education Trends 1.pdf -------------------------------------------------------------------------------- /Course 2 - Advanced Data Manipulation and Visualization in R/figures/Uganda Education Trends 2.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SebKrantz/Data-Science-Programme/1f0ea0ea50a940f950b09e684e610aa684756ac6/Course 2 - Advanced Data Manipulation and Visualization in R/figures/Uganda Education Trends 2.pdf -------------------------------------------------------------------------------- /Course 2 - Advanced Data Manipulation and Visualization in R/figures/Uganda Governance Statistics.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SebKrantz/Data-Science-Programme/1f0ea0ea50a940f950b09e684e610aa684756ac6/Course 2 - Advanced Data Manipulation and Visualization in R/figures/Uganda Governance Statistics.pdf -------------------------------------------------------------------------------- /Course 2 - Advanced Data Manipulation and Visualization in R/figures/World Wealth and Human Development.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SebKrantz/Data-Science-Programme/1f0ea0ea50a940f950b09e684e610aa684756ac6/Course 2 - Advanced Data Manipulation and Visualization in R/figures/World Wealth and Human Development.pdf -------------------------------------------------------------------------------- /Course 3 - Linear Modelling and Analysis + Extensions in R/Econometrics Academy/Instrumental Variables/Bachelor Level/Instrumental Variables Example.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SebKrantz/Data-Science-Programme/1f0ea0ea50a940f950b09e684e610aa684756ac6/Course 3 - Linear Modelling and Analysis + Extensions in R/Econometrics Academy/Instrumental Variables/Bachelor Level/Instrumental Variables Example.pdf -------------------------------------------------------------------------------- /Course 3 - Linear Modelling and Analysis + Extensions in R/Econometrics Academy/Instrumental Variables/Bachelor Level/Instrumental Variables R Program and Output.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SebKrantz/Data-Science-Programme/1f0ea0ea50a940f950b09e684e610aa684756ac6/Course 3 - Linear Modelling and Analysis + Extensions in R/Econometrics Academy/Instrumental Variables/Bachelor Level/Instrumental Variables R Program and Output.pdf -------------------------------------------------------------------------------- /Course 3 - Linear Modelling and Analysis + Extensions in R/Econometrics Academy/Instrumental Variables/Bachelor Level/Instrumental Variables in R.R: -------------------------------------------------------------------------------- 1 | # Instrumental Variables in R 2 | # Copyright 2013 by Ani Katchova 3 | 4 | # install.packages("AER") 5 | library(AER) 6 | # install.packages("systemfit") 7 | library(systemfit) 8 | 9 | mydata <- read.csv("C:/Econometrics/Data/iv_health.csv") 10 | attach(mydata) 11 | 12 | # Defining variables (Y1 dependent variable, Y2 endogenous variable) 13 | # (X1 exogenous variables, X2 instruments, X2 instruments, overidentified case) 14 | Y1 <- cbind(logmedexpense) 15 | Y2 <- cbind(healthinsu) 16 | X1 <- cbind(illnesses, age, logincome) 17 | X2 <- cbind(ssiratio) 18 | X2alt <- cbind(ssiratio, firmlocation) 19 | 20 | # Descriptive statistics 21 | summary(Y1) 22 | summary(Y2) 23 | summary(X1) 24 | summary(X2) 25 | 26 | # OLS regression 27 | olsreg <- lm(Y1 ~ Y2 + X1) 28 | summary(olsreg) 29 | 30 | # 2SLS estimation 31 | ivreg <- ivreg(Y1 ~ Y2 + X1 | X1 + X2) 32 | summary(ivreg) 33 | 34 | # 2SLS estimation (details) 35 | olsreg1 <- lm (Y2 ~ X1 + X2) 36 | summary(olsreg1) 37 | Y2hat <- fitted(olsreg1) 38 | 39 | olsreg2 <- lm(Y1 ~ Y2hat + X1) 40 | summary(olsreg2) 41 | 42 | # 2SLS estimation, over-identified case 43 | ivreg_o <- ivreg(Y1 ~ Y2 + X1 | X1 + X2alt) 44 | summary(ivreg_o) 45 | 46 | # Hausman test for endogeneity of regressors 47 | cf_diff <- coef(ivreg) - coef(olsreg) 48 | vc_diff <- vcov(ivreg) - vcov(olsreg) 49 | x2_diff <- as.vector(t(cf_diff) %*% solve(vc_diff) %*% cf_diff) 50 | pchisq(x2_diff, df = 2, lower.tail = FALSE) 51 | 52 | # Systems of equations 53 | 54 | # Defining equations for systems of equations (2SLS and 3SLS) 55 | # (X12 exogenous variable for eq2, X22 instrument for eq2) 56 | X12 <- cbind(illnesses) 57 | X22 <- cbind(firmlocation) 58 | eq1 <- Y1 ~ Y2 + X1 + X2 59 | eq2 <- Y2 ~ Y1 + X12 + X22 60 | inst <- ~ X1 + X2 + X22 61 | system <- list(eq1 = eq1, eq2 = eq2) 62 | 63 | # 2SLS estimation 64 | reg2sls <- systemfit(system, "2SLS", inst = inst, data = mydata) 65 | summary(reg2sls) 66 | 67 | # 3SLS estimation 68 | reg3sls <- systemfit(system, "3SLS", inst = inst, data = mydata) 69 | summary(reg3sls) 70 | -------------------------------------------------------------------------------- /Course 3 - Linear Modelling and Analysis + Extensions in R/Econometrics Academy/Instrumental Variables/Bachelor Level/Instrumental Variables.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SebKrantz/Data-Science-Programme/1f0ea0ea50a940f950b09e684e610aa684756ac6/Course 3 - Linear Modelling and Analysis + Extensions in R/Econometrics Academy/Instrumental Variables/Bachelor Level/Instrumental Variables.pdf -------------------------------------------------------------------------------- /Course 3 - Linear Modelling and Analysis + Extensions in R/Econometrics Academy/Instrumental Variables/Master Level/15 Instrumental Variables.R: -------------------------------------------------------------------------------- 1 | # Instrumental Variables 2 | 3 | # Outline: 4 | # IV estimation 5 | # 2SLS (two stage least squares) 6 | # Testing for endogeneity 7 | 8 | # Data files: 9 | # MROZ.csv 10 | 11 | # setup 12 | rm(list = ls()) 13 | directory <- "C:/Econometrics/DataR/" 14 | 15 | # Install packages 16 | PackageNames <- c("tidyverse", "stargazer", "magrittr", "haven", "AER") 17 | for(i in PackageNames){ 18 | if(!require(i, character.only = T)){ 19 | install.packages(i, dependencies = T) 20 | require(i, character.only = T) 21 | } 22 | } 23 | 24 | MROZ <- read.csv(paste0(directory, 'MROZ.csv')) 25 | 26 | # keep only working women 27 | MROZ %<>% filter(inlf == 1) 28 | 29 | MROZ %>% 30 | select(lwage, educ, exper, expersq, fatheduc, motheduc) %>% 31 | stargazer(type = "text") 32 | 33 | MROZ %>% 34 | select(lwage, educ, exper, expersq, fatheduc, motheduc) %>% 35 | head(10) 36 | 37 | # Regression model 38 | model1 <- lm(lwage ~ educ, MROZ) 39 | summary(model1) 40 | coef(model1)["educ"] 41 | 42 | 43 | # IV estimation ----------------------------------------------------------- 44 | 45 | # Dependent variable y, endogenous variable x, instrument z 46 | # Coefficient_ols = sum((x-xbar)*(y-ybar))/sum((x-xbar)*(x-xbar)) 47 | # Coefficient_iv = sum((z-zbar)*(y-ybar))/sum((z-zbar)*(x-xbar)) 48 | 49 | # Calculating means 50 | attach(MROZ) # attach MROZ so the variable names can be used directly 51 | mean_fatheduc <- mean(fatheduc) 52 | mean_educ <- mean(educ) 53 | mean_lwage <- mean(lwage) 54 | 55 | # OLS coefficient on educ 56 | numerator_ols <- (educ - mean_educ) * (lwage-mean_lwage) 57 | denominator_ols <- (educ - mean_educ) * (educ - mean_educ) 58 | sum_numerator_ols <- sum(numerator_ols) 59 | sum_denominator_ols <- sum(denominator_ols) 60 | 61 | (coeff_ols <- sum_numerator_ols/sum_denominator_ols) 62 | 63 | # IV coefficient on educ 64 | numerator_iv <- (fatheduc - mean_fatheduc) * (lwage - mean_lwage) 65 | denominator_iv <- (fatheduc - mean_fatheduc) * (educ - mean_educ) 66 | 67 | sum_numerator_iv <- sum(numerator_iv) 68 | sum_denominator_iv <- sum(denominator_iv) 69 | 70 | (coeff_iv <- sum_numerator_iv/sum_denominator_iv) 71 | detach(MROZ) 72 | 73 | 74 | # 2SLS (two stage least squares) ------------------------------------------ 75 | 76 | # Simple regression model with one instrument 77 | 78 | # OLS estimation 79 | summary(model1) 80 | 81 | # 2SLS 82 | model2 <- ivreg(formula = lwage ~ educ | . - educ + fatheduc, data = MROZ) 83 | summary(model2, diagnostics = TRUE) 84 | 85 | # 2SLS - first stage 86 | # Regression of endogenous variable educ on instrument fatheduc 87 | model3 <- lm(educ ~ fatheduc, MROZ) 88 | summary(model3) 89 | 90 | # Display R-squared of educ on fatheduc model 91 | summary(model3)$r.squared 92 | 93 | # Predicted values for educ_hat 94 | MROZ %<>% mutate(educ_hat = fitted(model3)) 95 | 96 | # Compare educ with educ_hat 97 | MROZ %>% select(educ, fatheduc, educ_hat) %>% head(10) 98 | 99 | # 2SLS - second stage 100 | # Replace educ with predicted value educ_hat 101 | model4 <- lm(lwage ~ educ_hat, MROZ) 102 | summary(model4) 103 | # Coefficients are correct but the standard errors are not correct 104 | 105 | 106 | # 2SLS (two stage least squares) ------------------------------------------ 107 | 108 | # Multiple regression model with several independent variables and two instruments 109 | 110 | # OLS estimation 111 | model5 <- lm(lwage ~ educ + exper + expersq, MROZ) 112 | summary(model5) 113 | 114 | # 2SLS 115 | model6 <- ivreg(lwage ~ educ + exper + expersq | . - educ + fatheduc + motheduc, 116 | data = MROZ) 117 | summary(model6) 118 | 119 | # 2SLS - first stage 120 | # Regression of endogenous variable educ on instruments fatheduc and motheduc 121 | model7 <- lm(educ ~ exper + expersq + fatheduc + motheduc, MROZ) 122 | summary(model7) 123 | 124 | # Testing whether educ and fatheduc and motheduc are correlated 125 | car::linearHypothesis(model7, c("fatheduc = 0", "motheduc = 0")) 126 | 127 | # Predicted values for educ_hat1 128 | MROZ %<>% mutate(educ_hat1 = fitted(model7)) 129 | 130 | # 2SLS - second stage 131 | # Replace endogenous variable educ with predicted value educ_hat1 132 | model8 <- lm(lwage ~ educ_hat1 + exper + expersq, MROZ) 133 | summary(model8) 134 | # Coefficients are correct but the standard errors are not correct 135 | 136 | # Testing for endogeneity ------------------------------------------------- 137 | # Testing for endogeneity of education in model for log wage 138 | 139 | # Structural equation 140 | summary(model5) 141 | 142 | # Estimate reduced form model for education 143 | model9 <- lm(educ ~ exper + expersq + fatheduc + motheduc, MROZ) 144 | summary(model9) 145 | # Predict the residuals vhat 146 | MROZ %<>% mutate(vhat = resid(model9)) 147 | 148 | # Structural equation for log wage that includes residuals vhat 149 | model10 <- update(model5, ~ . + vhat) 150 | summary(model10) 151 | 152 | # H0: coeff on vhat=0 (exogeneity) and H1: coeff on vhat ne 0 (endogeneity) 153 | # The coefficient on vhat is significant so education is endogenous. 154 | -------------------------------------------------------------------------------- /Course 3 - Linear Modelling and Analysis + Extensions in R/Econometrics Academy/Instrumental Variables/Master Level/15 Instrumental Variables.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SebKrantz/Data-Science-Programme/1f0ea0ea50a940f950b09e684e610aa684756ac6/Course 3 - Linear Modelling and Analysis + Extensions in R/Econometrics Academy/Instrumental Variables/Master Level/15 Instrumental Variables.pdf -------------------------------------------------------------------------------- /Course 3 - Linear Modelling and Analysis + Extensions in R/Econometrics Academy/Linear Regression/Bachelor Level/Linear Regression Example.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SebKrantz/Data-Science-Programme/1f0ea0ea50a940f950b09e684e610aa684756ac6/Course 3 - Linear Modelling and Analysis + Extensions in R/Econometrics Academy/Linear Regression/Bachelor Level/Linear Regression Example.pdf -------------------------------------------------------------------------------- /Course 3 - Linear Modelling and Analysis + Extensions in R/Econometrics Academy/Linear Regression/Bachelor Level/Linear Regression R Program and Output.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SebKrantz/Data-Science-Programme/1f0ea0ea50a940f950b09e684e610aa684756ac6/Course 3 - Linear Modelling and Analysis + Extensions in R/Econometrics Academy/Linear Regression/Bachelor Level/Linear Regression R Program and Output.pdf -------------------------------------------------------------------------------- /Course 3 - Linear Modelling and Analysis + Extensions in R/Econometrics Academy/Linear Regression/Bachelor Level/Linear Regression in R.R: -------------------------------------------------------------------------------- 1 | # Linear Regression in R 2 | # Copyright 2013 by Ani Katchova 3 | 4 | mydata<- read.csv("C:/Econometrics/Data/regression_auto.csv") 5 | attach(mydata) 6 | 7 | # Define variables 8 | Y <- cbind(mpg) 9 | X1 <- cbind(weight1) 10 | X <- cbind(weight1, price, foreign) 11 | 12 | # Descriptive statistics 13 | summary(Y) 14 | summary(X) 15 | 16 | # Correlation among variables 17 | cor(Y, X) 18 | 19 | # Plotting data on a scatter diagram 20 | plot(Y ~ X1, data = mydata) 21 | 22 | # Simple linear regression 23 | olsreg1 <- lm(Y ~ X1) 24 | summary(olsreg1) 25 | confint(olsreg1, level=0.95) 26 | anova(olsreg1) 27 | 28 | # Plotting regression line 29 | abline(olsreg1) 30 | 31 | # Predicted values for dependent variable 32 | Y1hat <- fitted(olsreg1) 33 | summary(Y1hat) 34 | plot(Y1hat ~ X1) 35 | 36 | # Regression residuals 37 | e1hat <- resid(olsreg1) 38 | summary(e1hat) 39 | plot(e1hat ~ X1) 40 | 41 | # Multiple linear regression 42 | olsreg2 <- lm(Y ~ X) 43 | summary(olsreg2) 44 | confint(olsreg2, level=0.95) 45 | anova(olsreg2) 46 | 47 | # Predicted values for dependent variable 48 | Yhat <- fitted(olsreg2) 49 | summary(Yhat) 50 | 51 | # Regression residuals 52 | ehat <- resid(olsreg2) 53 | summary(ehat) 54 | -------------------------------------------------------------------------------- /Course 3 - Linear Modelling and Analysis + Extensions in R/Econometrics Academy/Linear Regression/Bachelor Level/Linear Regression.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SebKrantz/Data-Science-Programme/1f0ea0ea50a940f950b09e684e610aa684756ac6/Course 3 - Linear Modelling and Analysis + Extensions in R/Econometrics Academy/Linear Regression/Bachelor Level/Linear Regression.pdf -------------------------------------------------------------------------------- /Course 3 - Linear Modelling and Analysis + Extensions in R/Econometrics Academy/Linear Regression/Bachelor Level/regression_auto.csv: -------------------------------------------------------------------------------- 1 | make,mpg,weight,weight1,price,foreign,repairs,length 2 | "AMC",22,2930,2.93,4099,0,3,186 3 | "AMC",17,3350,3.35,4749,0,3,173 4 | "AMC",22,2640,2.64,3799,0,3,168 5 | "Audi",17,2830,2.83,9690,1,5,189 6 | "Audi",23,2070,2.07,6295,1,3,174 7 | "BMW",25,2650,2.65,9735,1,4,177 8 | "Buick",20,3250,3.25,4816,0,3,196 9 | "Buick",15,4080,4.08,7827,0,4,222 10 | "Buick",18,3670,3.67,5788,0,3,218 11 | "Buick",26,2230,2.23,4453,0,3,170 12 | "Buick",20,3280,3.28,5189,0,3,200 13 | "Buick",16,3880,3.88,10372,0,3,207 14 | "Buick",19,3400,3.4,4082,0,3,200 15 | "Cadillac",14,4330,4.33,11385,0,3,221 16 | "Cadillac",14,3900,3.9,14500,0,2,204 17 | "Cadillac",21,4290,4.29,15906,0,3,204 18 | "Chevrolet",29,2110,2.11,3299,0,3,163 19 | "Chevrolet",16,3690,3.69,5705,0,4,212 20 | "Chevrolet",22,3180,3.18,4504,0,3,193 21 | "Chevrolet",22,3220,3.22,5104,0,2,200 22 | "Chevrolet",24,2750,2.75,3667,0,2,179 23 | "Chevrolet",19,3430,3.43,3955,0,3,197 24 | "Datsun",23,2370,2.37,6229,1,4,170 25 | "Datsun",35,2020,2.02,4589,1,5,165 26 | "Datsun",24,2280,2.28,5079,1,4,170 27 | "Datsun",21,2750,2.75,8129,1,4,184 28 | -------------------------------------------------------------------------------- /Course 3 - Linear Modelling and Analysis + Extensions in R/Econometrics Academy/Linear Regression/Master Level/3 Multiple Regression Model.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SebKrantz/Data-Science-Programme/1f0ea0ea50a940f950b09e684e610aa684756ac6/Course 3 - Linear Modelling and Analysis + Extensions in R/Econometrics Academy/Linear Regression/Master Level/3 Multiple Regression Model.pdf -------------------------------------------------------------------------------- /Course 3 - Linear Modelling and Analysis + Extensions in R/Econometrics Academy/Panel Data Models/Bachelor Level/Panel Data Models Example.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SebKrantz/Data-Science-Programme/1f0ea0ea50a940f950b09e684e610aa684756ac6/Course 3 - Linear Modelling and Analysis + Extensions in R/Econometrics Academy/Panel Data Models/Bachelor Level/Panel Data Models Example.pdf -------------------------------------------------------------------------------- /Course 3 - Linear Modelling and Analysis + Extensions in R/Econometrics Academy/Panel Data Models/Bachelor Level/Panel Data Models R Program and Output.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SebKrantz/Data-Science-Programme/1f0ea0ea50a940f950b09e684e610aa684756ac6/Course 3 - Linear Modelling and Analysis + Extensions in R/Econometrics Academy/Panel Data Models/Bachelor Level/Panel Data Models R Program and Output.pdf -------------------------------------------------------------------------------- /Course 3 - Linear Modelling and Analysis + Extensions in R/Econometrics Academy/Panel Data Models/Bachelor Level/Panel Data Models in R.R: -------------------------------------------------------------------------------- 1 | # Panel Data Models in R 2 | 3 | 4 | install.packages("plm") 5 | library(plm) 6 | 7 | mydata<- read.csv("C:/Econometrics/Data/panel_wage.csv") 8 | attach(mydata) 9 | 10 | Y <- cbind(lwage) 11 | X <- cbind(exp, exp2, wks, ed) 12 | 13 | # Set data as panel data 14 | pdata <- pdata.frame(mydata, index=c("id","t")) 15 | 16 | # Descriptive statistics 17 | summary(Y) 18 | summary(X) 19 | 20 | # Pooled OLS estimator 21 | pooling <- plm(Y ~ X, data=pdata, model= "pooling") 22 | summary(pooling) 23 | 24 | # Between estimator 25 | between <- plm(Y ~ X, data=pdata, model= "between") 26 | summary(between) 27 | 28 | # First differences estimator 29 | firstdiff <- plm(Y ~ X, data=pdata, model= "fd") 30 | summary(firstdiff) 31 | 32 | # Fixed effects or within estimator 33 | fixed <- plm(Y ~ X, data=pdata, model= "within") 34 | summary(fixed) 35 | 36 | # Random effects estimator 37 | random <- plm(Y ~ X, data=pdata, model= "random") 38 | summary(random) 39 | 40 | # LM test for random effects versus OLS 41 | plmtest(pooling) 42 | 43 | # LM test for fixed effects versus OLS 44 | pFtest(fixed, pooling) 45 | 46 | # Hausman test for fixed versus random effects model 47 | phtest(random, fixed) 48 | -------------------------------------------------------------------------------- /Course 3 - Linear Modelling and Analysis + Extensions in R/Econometrics Academy/Panel Data Models/Bachelor Level/Panel Data Models.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SebKrantz/Data-Science-Programme/1f0ea0ea50a940f950b09e684e610aa684756ac6/Course 3 - Linear Modelling and Analysis + Extensions in R/Econometrics Academy/Panel Data Models/Bachelor Level/Panel Data Models.pdf -------------------------------------------------------------------------------- /Course 3 - Linear Modelling and Analysis + Extensions in R/Econometrics Academy/Panel Data Models/Master Level/14 Panel Data Model.R: -------------------------------------------------------------------------------- 1 | # Panel Data Models 2 | 3 | # Outline: 4 | # Pooled OLS estimator 5 | # Between estimator 6 | # First differences estimator 7 | # Fixed effects within estimator 8 | # Dummy variables regression 9 | # Random effects estimator 10 | # Hausman test for fixed versus random effects 11 | 12 | # Data files: 13 | # JTRAIN.csv 14 | 15 | # setup 16 | rm(list = ls()) 17 | directory <- "C:/Econometrics/DataR/" 18 | 19 | # Install packages 20 | PackageNames <- c("tidyverse", "stargazer", "magrittr", "haven", "plm") 21 | for(i in PackageNames){ 22 | if(!require(i, character.only = T)){ 23 | install.packages(i, dependencies = T) 24 | require(i, character.only = T) 25 | } 26 | } 27 | 28 | # Example: Effect of training grants on firm scrap rate ------------------- 29 | JTRAIN <- read.csv(paste0(directory, 'JTRAIN.csv')) 30 | 31 | # Drop missing observations for dependent variable 32 | JTRAIN %<>% filter(!is.na(lscrap)) 33 | 34 | # Keep the variables needed 35 | JTRAIN %<>% select(fcode, year, lscrap, tothrs, d88, d89, grant, grant_1) 36 | 37 | # Describe and summarize 38 | JTRAIN %>% str 39 | JTRAIN %>% head(9) 40 | JTRAIN %>% stargazer(type = "text") 41 | 42 | # Panel data where fcode is the cross sectional dimension and year is the time series dimension 43 | 44 | # Number of observations 45 | JTRAIN %>% group_by(fcode) %>% summarize(n = n()) # number of obs by 'fcode' 46 | JTRAIN %>% group_by(year) %>% summarize(n = n()) # number of obs by 'year' 47 | 48 | # Overall variations 49 | JTRAIN %>% 50 | select(lscrap, tothrs, d88, d89, grant, grant_1) %>% 51 | mutate_all(function(x) {x - mean(x, na.rm= T)}) %>% # variable - overall mean 52 | as.data.frame %>% 53 | stargazer(type = "text", omit.summary.stat = "mean", digits = 2) 54 | 55 | # Between variations 56 | JTRAIN %>% group_by(fcode) %>% 57 | select(lscrap, tothrs, d88, d89, grant, grant_1) %>% 58 | summarize_all(mean) %>% 59 | as.data.frame %>% 60 | select(-fcode) %>% 61 | stargazer(type = "text", digits = 2) 62 | 63 | # Within variations 64 | JTRAIN %>% group_by(fcode) %>% 65 | select(lscrap, tothrs, d88, d89, grant, grant_1) %>% 66 | mutate_all(function(x) {x - mean(x)}) %>% # demean 67 | as.data.frame %>% 68 | select(-fcode) %>% 69 | stargazer(type = "text", omit.summary.stat = "mean", digits =2) 70 | 71 | 72 | # Pooled OLS, between, and first differences estimator -------------------- 73 | 74 | # Pooled OLS estimator 75 | model_ols <- plm(formula = lscrap ~ tothrs + d88 + d89 + grant + grant_1, 76 | data = JTRAIN, 77 | index = c("fcode", "year"), # c(group index, time index) 78 | model = "pooling") 79 | summary(model_ols) 80 | 81 | # Between estimator 82 | model_be <- update(model_ols, model = "between") 83 | summary(model_be) 84 | 85 | # Taking first differences 86 | diff <- function(x) {x - dplyr::lag(x)} 87 | JTRAIN %<>% 88 | group_by(fcode) %>% 89 | mutate(dlscrap = diff(lscrap), 90 | dtothrs = diff(tothrs), 91 | dgrant = diff(grant)) %>% 92 | ungroup() 93 | 94 | # First differences estimator 95 | model_fd <- lm(dlscrap ~ dtothrs + dgrant, JTRAIN) 96 | summary(model_fd) 97 | 98 | 99 | # Fixed effects within estimator ------------------------------------------ 100 | 101 | # Fixed effects within estimator 102 | # model_fe <- update(model_ols, model = "within", effect = "individual") 103 | model_fe <- plm(formula = lscrap ~ tothrs + d88 + d89 + grant + grant_1, 104 | data = JTRAIN, 105 | index = c("fcode", "year"), # c(group index, time index) 106 | model = "within", effect = "individual") 107 | summary(model_fe) 108 | 109 | # Summarize the individual specific effects a_i 110 | ai <- fixef(model_fe, type = "dmean") # extract fixed effects using 'fixef' 111 | ai %>% head(10) 112 | summary(ai) # 'summary' shows the p-value table 113 | data.frame(ai) %>% stargazer(type = "text") # summarize 114 | 115 | 116 | # Dummy variables regression ---------------------------------------------- 117 | 118 | # Dummy variables regression with fixed effects 119 | # model_dv <- update(model_ols, ~ . + factor(fcode)) 120 | model_dv <- plm(formula = lscrap ~ tothrs + d88 + d89 + grant + grant_1 + factor(fcode), 121 | data = JTRAIN, 122 | index = c("fcode", "year"), # c(group index, time index) 123 | model = "pooling") 124 | summary(model_dv) 125 | # factor(fcode) creates one dummy variable for each fcode 126 | 127 | # R-squared for fixed effects estimator and dummy variables regression 128 | summary(model_fe) 129 | yhat <- fitted(model_fe) 130 | y <- pmodel.response(model_fe) # demeaned y 131 | (mss <- sum((yhat - mean(y))^2)) 132 | (ess <- sum(resid(model_fe)^2)) 133 | (rsquared0 <- mss / (mss + ess)) 134 | 135 | summary(model_dv) 136 | yhat <- fitted(model_dv) 137 | y <- pmodel.response(model_dv) 138 | (mss <- sum((yhat - mean(y))^2)) 139 | (ess <- sum(resid(model_fe)^2)) 140 | (rsquared <- mss / (mss + ess)) 141 | 142 | 143 | # Random effects estimator ------------------------------------------------ 144 | 145 | # Random effects estimator 146 | # model_re <- update(model_ols, model = "random", random.method = "walhus") 147 | model_re <- plm(formula = lscrap ~ tothrs + d88 + d89 + grant + grant_1, 148 | data = JTRAIN, 149 | index = c("fcode", "year"), # c(group index, time index) 150 | model = "random", random.method = "walhus") 151 | summary(model_re) 152 | # The theta parameter is listed in the summary 153 | 154 | # Calculate the random effects parameter theta 155 | (sigma2_e <- model_re$ercomp$sigma2["idios"]) 156 | (sigma2_u <- model_re$ercomp$sigma2["id"]) 157 | (theta <- 1 - sqrt(sigma2_e / (sigma2_e + 3*sigma2_u))) 158 | 159 | 160 | # Hausman test for fixed versus random effects ---------------------------- 161 | 162 | # The Hausman test is used to decide whether to use fixed effects or random effects. 163 | # H0: FE coefficients are not significantly different from the RE coefficients 164 | # Ha: FE coefficients are significantly different from the RE coefficients 165 | 166 | # Fixed effects estimator 167 | summary(model_fe) 168 | 169 | # Random effects estimator 170 | summary(model_re) 171 | 172 | # Hausman test for fixed versus random effects 173 | phtest(model_fe, model_re) 174 | # If the Hausman test statistic is insignificant, use RE estimator because it is efficient 175 | # If the Hausman test statistic is significant, use FE estimator because it is consistent 176 | -------------------------------------------------------------------------------- /Course 3 - Linear Modelling and Analysis + Extensions in R/Econometrics Academy/Panel Data Models/Master Level/14 Panel Data Models.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SebKrantz/Data-Science-Programme/1f0ea0ea50a940f950b09e684e610aa684756ac6/Course 3 - Linear Modelling and Analysis + Extensions in R/Econometrics Academy/Panel Data Models/Master Level/14 Panel Data Models.pdf -------------------------------------------------------------------------------- /Course 3 - Linear Modelling and Analysis + Extensions in R/Econometrics Academy/Probit and Logit Models/Bachelor level/Probit and Logit Models Example.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SebKrantz/Data-Science-Programme/1f0ea0ea50a940f950b09e684e610aa684756ac6/Course 3 - Linear Modelling and Analysis + Extensions in R/Econometrics Academy/Probit and Logit Models/Bachelor level/Probit and Logit Models Example.pdf -------------------------------------------------------------------------------- /Course 3 - Linear Modelling and Analysis + Extensions in R/Econometrics Academy/Probit and Logit Models/Bachelor level/Probit and Logit Models R Program and Output.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SebKrantz/Data-Science-Programme/1f0ea0ea50a940f950b09e684e610aa684756ac6/Course 3 - Linear Modelling and Analysis + Extensions in R/Econometrics Academy/Probit and Logit Models/Bachelor level/Probit and Logit Models R Program and Output.pdf -------------------------------------------------------------------------------- /Course 3 - Linear Modelling and Analysis + Extensions in R/Econometrics Academy/Probit and Logit Models/Bachelor level/Probit and Logit Models in R.R: -------------------------------------------------------------------------------- 1 | # Probit and Logit Models in R 2 | # Copyright 2013 by Ani Katchova 3 | 4 | mydata<- read.csv("C:/Econometrics/Data/probit_insurance.csv") 5 | attach(mydata) 6 | 7 | # Define variables 8 | Y <- cbind(ins) 9 | X <- cbind(retire, age, hstatusg, hhincome, educyear, married, hisp) 10 | 11 | # Descriptive statistics 12 | summary(Y) 13 | summary(X) 14 | 15 | table(Y) 16 | table(Y)/sum(table(Y)) 17 | 18 | # Regression coefficients 19 | olsreg <- lm(Y ~ X) 20 | summary(olsreg) 21 | 22 | # Logit model coefficients 23 | logit<- glm(Y ~ X, family=binomial (link = "logit")) 24 | summary(logit) 25 | 26 | # Logit model odds ratios 27 | exp(logit$coefficients) 28 | 29 | # Probit model coefficients 30 | probit<- glm(Y ~ X, family=binomial (link="probit")) 31 | summary(probit) 32 | 33 | 34 | # Regression marginal effects 35 | coef(olsreg) 36 | 37 | # Logit model average marginal effects 38 | LogitScalar <- mean(dlogis(predict(logit, type = "link"))) 39 | LogitScalar * coef(logit) 40 | 41 | # Probit model average marginal effects 42 | ProbitScalar <- mean(dnorm(predict(probit, type = "link"))) 43 | ProbitScalar * coef(probit) 44 | 45 | 46 | # Regression predicted probabilities 47 | polsreg<- predict(olsreg) 48 | summary(polsreg) 49 | 50 | # Logit model predicted probabilities 51 | plogit<- predict(logit, type="response") 52 | summary(plogit) 53 | 54 | # Probit model predicted probabilities 55 | pprobit<- predict(probit, type="response") 56 | summary(pprobit) 57 | 58 | 59 | # Percent correctly predicted values 60 | table(true = Y, pred = round(fitted(probit))) 61 | table(true = Y, pred = round(fitted(logit))) 62 | 63 | # McFadden's Pseudo R-squared 64 | probit0<-update(probit, formula= Y ~ 1) 65 | McFadden<- 1-as.vector(logLik(probit)/logLik(probit0)) 66 | McFadden 67 | -------------------------------------------------------------------------------- /Course 3 - Linear Modelling and Analysis + Extensions in R/Econometrics Academy/Probit and Logit Models/Bachelor level/Probit and Logit Models.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SebKrantz/Data-Science-Programme/1f0ea0ea50a940f950b09e684e610aa684756ac6/Course 3 - Linear Modelling and Analysis + Extensions in R/Econometrics Academy/Probit and Logit Models/Bachelor level/Probit and Logit Models.pdf -------------------------------------------------------------------------------- /Course 3 - Linear Modelling and Analysis + Extensions in R/Econometrics Academy/Probit and Logit Models/Master Level/17 Probit and Logit Models.R: -------------------------------------------------------------------------------- 1 | # Probit and Logit Models 2 | 3 | # Outline: 4 | # Probit and logit models 5 | # Predicted probabilities 6 | # Marginal effects 7 | # Pseudo R-squared 8 | # Percent correctly predicted 9 | 10 | # Data files: 11 | # MROZ.csv 12 | 13 | # setup 14 | rm(list = ls()) 15 | directory <- "C:/Econometrics/DataR/" 16 | 17 | # Install packages 18 | PackageNames <- c("tidyverse", "stargazer", "magrittr", "margins", "caret") 19 | for(i in PackageNames){ 20 | if(!require(i, character.only = T)){ 21 | install.packages(i, dependencies = T) 22 | require(i, character.only = T) 23 | } 24 | } 25 | 26 | # Probit and logit models ------------------------------------------------ 27 | 28 | # Model of being in labor force for women 29 | MROZ <- read.csv(paste0(directory, 'MROZ.csv')) 30 | 31 | MROZ %>% select(inlf, nwifeinc, educ, exper, age, kidslt6) %>% str 32 | MROZ %>% select(inlf, nwifeinc, educ, exper, age, kidslt6) %>% head(10) 33 | MROZ %>% select(inlf, nwifeinc, educ, exper, age, kidslt6) %>% stargazer(type = "text") 34 | count(MROZ, inlf) 35 | 36 | # Linear probability model (LPM) 37 | LPM <- lm(inlf ~ nwifeinc + educ + exper + age + kidslt6, MROZ) 38 | summary(LPM) 39 | 40 | # Probit model 41 | Probit <- glm(formula = inlf ~ nwifeinc + educ + exper + age + kidslt6, 42 | family = binomial(link = "probit"), 43 | data = MROZ) 44 | summary(Probit) 45 | 46 | # Logit model 47 | Logit <- glm(formula = inlf ~ nwifeinc + educ + exper + age + kidslt6, 48 | family = binomial(link = "logit"), 49 | data = MROZ) 50 | summary(Logit) 51 | 52 | # Predicted probabilities ------------------------------------------------- 53 | # Predicted probabilities for LPM 54 | MROZ %<>% mutate(inlfhat_lpm = fitted(LPM)) 55 | 56 | # Predicted probabilities for probit model 57 | MROZ %<>% mutate(inlfhat_probit = fitted(Probit)) 58 | 59 | # Predicted probabilities for logit model 60 | MROZ %<>% mutate(inlfhat_logit = fitted(Logit)) 61 | 62 | # Summarize predicted values for inlf 63 | MROZ %>% select(inlf, inlfhat_lpm, inlfhat_probit, inlfhat_logit) %>% 64 | stargazer(type = "text") 65 | MROZ %>% select(inlf, inlfhat_lpm, inlfhat_probit, inlfhat_logit) %>% 66 | head(5) 67 | MROZ %>% select(inlf, inlfhat_lpm, inlfhat_probit, inlfhat_logit) %>% 68 | .[601:605, ] 69 | 70 | 71 | # Marginal effects -------------------------------------------------------- 72 | 73 | # Linear probability model (LPM) 74 | summary(LPM) 75 | coef(LPM) 76 | # Coefficients are marginal effects in a linear model 77 | 78 | # Probit model 79 | summary(Probit) 80 | Mean <- model.frame(Probit) %>% 81 | map_df(mean) # mean of independent variables 82 | 83 | # Probit - marginal effect at the mean 84 | Probit.atmean <- margins(Probit, at = Mean) 85 | summary(Probit.atmean) 86 | 87 | # Probit - average marginal effect 88 | Probit.AME <- margins(Probit) 89 | summary(Probit.AME) 90 | 91 | # Logit model 92 | summary(Logit) 93 | 94 | # Logit - marginal effect at the mean 95 | Logit.atmean <- margins(Logit, at = Mean) 96 | summary(Logit.atmean) 97 | 98 | # Logit - average marginal effect 99 | Logit.AME <- margins(Logit) 100 | summary(Logit.AME) 101 | 102 | # Pseudo R-squared -------------------------------------------------------- 103 | 104 | # Probit model - unrestricted model with all variables 105 | summary(Probit) 106 | 107 | # Probit model - unrestricted model with all variables 108 | ur.model <- Probit 109 | summary(ur.model) 110 | 111 | # Log-likelihood for unrestricted model 112 | (LLur <- logLik(ur.model)) 113 | 114 | # Probit restricted model with only constant 115 | r.model <- glm(inlf ~ 1, binomial(link = "probit"), data = MROZ) 116 | summary(r.model) 117 | 118 | # Log-likelihood for model with only constant 119 | (LL0 <- logLik(r.model)) 120 | 121 | # Calculate pseudo R-squared 122 | (pseudo_r2 <- 1 - LLur/LL0) 123 | 124 | 125 | # Percent correctly predicted --------------------------------------------- 126 | 127 | # Percent correctly predicted for probit model 128 | (Probit.pred <- (fitted(Probit) > 0.5) %>% as.numeric %>% as.factor) # Prediction 129 | (actual <- MROZ$inlf %>% as.factor) # actual data 130 | caret::confusionMatrix(Probit.pred, actual, positive = "1") 131 | 132 | # Percent correctly predicted for logit model 133 | (Logit.pred <- (fitted(Logit) > 0.5) %>% as.numeric %>% as.factor) # Prediction 134 | confusionMatrix(Logit.pred, actual, positive = "1") 135 | -------------------------------------------------------------------------------- /Course 3 - Linear Modelling and Analysis + Extensions in R/Econometrics Academy/Probit and Logit Models/Master Level/17 Probit and Logit Models.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SebKrantz/Data-Science-Programme/1f0ea0ea50a940f950b09e684e610aa684756ac6/Course 3 - Linear Modelling and Analysis + Extensions in R/Econometrics Academy/Probit and Logit Models/Master Level/17 Probit and Logit Models.pdf -------------------------------------------------------------------------------- /Course 3 - Linear Modelling and Analysis + Extensions in R/factors.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SebKrantz/Data-Science-Programme/1f0ea0ea50a940f950b09e684e610aa684756ac6/Course 3 - Linear Modelling and Analysis + Extensions in R/factors.pdf -------------------------------------------------------------------------------- /Course 3 - Linear Modelling and Analysis + Extensions in R/logmodels2.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SebKrantz/Data-Science-Programme/1f0ea0ea50a940f950b09e684e610aa684756ac6/Course 3 - Linear Modelling and Analysis + Extensions in R/logmodels2.pdf -------------------------------------------------------------------------------- /Course 3 - Linear Modelling and Analysis + Extensions in R/probability-statistics.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SebKrantz/Data-Science-Programme/1f0ea0ea50a940f950b09e684e610aa684756ac6/Course 3 - Linear Modelling and Analysis + Extensions in R/probability-statistics.pdf -------------------------------------------------------------------------------- /Course 4 - Time Series Analysis and Forecasting in R/C4_S2.R: -------------------------------------------------------------------------------- 1 | ############################################################# 2 | # *************** R BASED DATA SCIENCE TRAINING ************* 3 | # Course 4: Time Series Analysis and Forecasting with R 4 | # ----------------------------------------------------------- 5 | # Prepared by: Sebastian Krantz, ODI Fellow, MEPD, MoFPED 6 | # Permanent Contact: sebastian.krantz@graduateinstitute.ch 7 | ############################################################# 8 | 9 | 10 | # Today: 11 | # (7) Automatic Forecast Method Selection 12 | # (8) Non-Linear Methods (Neural Networks, Boosted Trees) 13 | # (9) Forecasting with a large number of series (Ridge regression, Partial least squares) 14 | 15 | 16 | # (7) Automatic Forecast Method Selection 17 | library(autoTS) 18 | ugatsdb_reconnect() 19 | CPI <- ugatsdb::get_data("BOU_MMI", "CPI_HL_09") 20 | best.algo <- getBestModel(CPI$Date, CPI$CPI_HL_09, "month", n_test = 48, metric.error = my.mae) 21 | names(best.algo) 22 | print(paste("The best algorithm is", best.algo$best)) 23 | best.algo$train.errors 24 | final.pred <- my.predictions(bestmod = best.algo) 25 | 26 | library(tsSelect) 27 | CPI_ts <- ts(CPI$CPI_HL_09, start = c(2005, 7), frequency = 12) 28 | bm <- run_models(CPI_ts, accuracy_measure = "MAE") 29 | 30 | # (8) Non-Linear Methods (Neural Networks, Boosted Trees) 31 | library(forecast) 32 | nnetar_mod <- nnetar(CPI_ts) 33 | plot(forecast(nnetar_mod, h = 10)) 34 | 35 | library(nnfor) 36 | elm_mod <- elm(CPI_ts) 37 | plot(elm_mod) 38 | plot(forecast(elm_mod, h = 10)) 39 | 40 | mlp_mod <- mlp(CPI_ts) 41 | plot(mlp_mod) 42 | plot(forecast(mlp_mod, h = 10)) 43 | 44 | library(forecastxgb) 45 | mod <- xgbar(CPI_ts, seas_method = "decompose") 46 | plot(forecast(mod, h = 10)) 47 | 48 | library(iForecast) 49 | ttsCPI <- ttsCaret(as.xts(CPI), method = c("svm","rf","rpart","gamboost","BstLm","bstSm","blackboost"), 50 | train.end = "2018-01-01", type = "both") 51 | P2 <- iForecast(Model=ttsCPI,newdata=CPI,type="recursive") 52 | 53 | 54 | CPI_LSTM <- ttsLSTM(as.xts(CPI), train.end = "2018-01-01", type = "both") 55 | 56 | 57 | 58 | # (9) Forecasting with a large number of series (Ridge regression, Partial least squares) 59 | 60 | 61 | library(glmnet) # Ridge Regression 62 | library(pls) # Partial Least Squares 63 | 64 | -------------------------------------------------------------------------------- /Course 4 - Time Series Analysis and Forecasting in R/data/exercise1.xlsx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SebKrantz/Data-Science-Programme/1f0ea0ea50a940f950b09e684e610aa684756ac6/Course 4 - Time Series Analysis and Forecasting in R/data/exercise1.xlsx -------------------------------------------------------------------------------- /Course 4 - Time Series Analysis and Forecasting in R/resources/ARMA Selection.PNG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SebKrantz/Data-Science-Programme/1f0ea0ea50a940f950b09e684e610aa684756ac6/Course 4 - Time Series Analysis and Forecasting in R/resources/ARMA Selection.PNG -------------------------------------------------------------------------------- /Course 4 - Time Series Analysis and Forecasting in R/resources/Forecasting with R Data Camp Course Slides/chapter1.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SebKrantz/Data-Science-Programme/1f0ea0ea50a940f950b09e684e610aa684756ac6/Course 4 - Time Series Analysis and Forecasting in R/resources/Forecasting with R Data Camp Course Slides/chapter1.pdf -------------------------------------------------------------------------------- /Course 4 - Time Series Analysis and Forecasting in R/resources/Forecasting with R Data Camp Course Slides/chapter2.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SebKrantz/Data-Science-Programme/1f0ea0ea50a940f950b09e684e610aa684756ac6/Course 4 - Time Series Analysis and Forecasting in R/resources/Forecasting with R Data Camp Course Slides/chapter2.pdf -------------------------------------------------------------------------------- /Course 4 - Time Series Analysis and Forecasting in R/resources/Forecasting with R Data Camp Course Slides/chapter3.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SebKrantz/Data-Science-Programme/1f0ea0ea50a940f950b09e684e610aa684756ac6/Course 4 - Time Series Analysis and Forecasting in R/resources/Forecasting with R Data Camp Course Slides/chapter3.pdf -------------------------------------------------------------------------------- /Course 4 - Time Series Analysis and Forecasting in R/resources/Forecasting with R Data Camp Course Slides/chapter4.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SebKrantz/Data-Science-Programme/1f0ea0ea50a940f950b09e684e610aa684756ac6/Course 4 - Time Series Analysis and Forecasting in R/resources/Forecasting with R Data Camp Course Slides/chapter4.pdf -------------------------------------------------------------------------------- /Course 4 - Time Series Analysis and Forecasting in R/resources/Forecasting with R Data Camp Course Slides/chapter5.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SebKrantz/Data-Science-Programme/1f0ea0ea50a940f950b09e684e610aa684756ac6/Course 4 - Time Series Analysis and Forecasting in R/resources/Forecasting with R Data Camp Course Slides/chapter5.pdf -------------------------------------------------------------------------------- /Course 4 - Time Series Analysis and Forecasting in R/resources/Macroeconomic Forecasting with ECM's and DLM's/GDP_REV_Q.xlsx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SebKrantz/Data-Science-Programme/1f0ea0ea50a940f950b09e684e610aa684756ac6/Course 4 - Time Series Analysis and Forecasting in R/resources/Macroeconomic Forecasting with ECM's and DLM's/GDP_REV_Q.xlsx -------------------------------------------------------------------------------- /Course 4 - Time Series Analysis and Forecasting in R/resources/Macroeconomic Forecasting with ECM's and DLM's/ME_FC_ECM_DLM_PCK_FUN.R: -------------------------------------------------------------------------------- 1 | library(readxl) # Import from Excel 2 | library(collapse) # Data transformation and time series operators 3 | library(magrittr) # Pipe operators %>%, %$% 4 | library(tseries) # Time series tests 5 | library(lmtest) # Linear model tests 6 | library(sandwich) # Robust standard errors 7 | library(jtools) # Enhanced regression summary 8 | library(xts) # Extensible time series + pretty plots 9 | 10 | 11 | # Function to compute a correlogram of a time series 12 | corrgram <- function(x, lag.max = NULL, plot = FALSE, 13 | na.action = function(x) if(anyNA(unclass(x))) 14 | x[!is.na(x)] else x) { 15 | if(plot) { 16 | oldpar <- par(mfrow = c(1L, 2L)) 17 | on.exit(par(oldpar)) 18 | } 19 | ac <- eval(substitute(acf(x, lag.max, plot = plot, na.action = na.action))) 20 | acf <- drop(ac[[1L]])[-1L] 21 | pacf <- drop(eval(substitute(pacf(x, lag.max, plot = plot, 22 | na.action = na.action)))[[1L]]) 23 | n <- ac$n.used 24 | qstat <- n * (n + 2) * cumsum(acf^2 / seq.int(n - 1, n - length(acf))) 25 | lags <- seq_along(acf) 26 | res <- cbind(Lag = lags, AC = acf, PAC = pacf, 27 | Q = qstat, `Pr(>Q)` = pchisq(qstat, lags, lower.tail = FALSE)) 28 | class(res) <- "corrgram" 29 | res 30 | } 31 | 32 | # Print method 33 | print.corrgram <- function(x, digits = 3, ...) { 34 | xx <- cbind(format(x[, 1L, drop = FALSE], drop0trailing = TRUE), 35 | format(round(x[, -1L], digits))) 36 | print.default(`rownames<-`(xx, rep(" ", nrow(xx))), quote = FALSE, right = TRUE) 37 | } 38 | 39 | # Function to forecast n periods in-sample for forecast evaluation 40 | forecast_is <- function(model, data, n = 1L) { 41 | data <- qDF(na_omit(data)) 42 | N <- nrow(data) 43 | s <- (N-n):(N-1L) 44 | form <- terms(model) 45 | y <- attr(form, "variables")[1:2] 46 | # Dependent variable and forecast are returned as in the model (e.g. differenced) 47 | ydat <- qDF(eval(y, data, parent.frame())) 48 | names(ydat) <- deparse(y[[2L]]) 49 | # Forecasting with expanding window 50 | fc <- numeric(0L) 51 | for(i in s) { 52 | # This re-estimates the model on the selected sample 53 | reest <- lm(form, ss(data, seq_len(i))) 54 | # This forecasts one period ahead 55 | fc <- c(fc, flast(predict(reest, newdata = ss(data, seq_len(i+1L))))) 56 | } 57 | ydat[s + 1L, "fc"] <- unattrib(fc) 58 | return(ydat) 59 | } 60 | 61 | eval_forecasts <- function(y, fc, add.naive = TRUE, n.ahead = 1) { 62 | # eval substitute to get the name of the forecast if only a vector is passed 63 | mfc <- eval(substitute(qDF(fc))) 64 | lagy <- flag(y, n.ahead) 65 | if (add.naive) mfc <- c(list(Naive = lagy), mfc) 66 | if (!all(length(y) == lengths(mfc))) 67 | stop("All supplied quantities must be of equal length") 68 | res <- vapply(mfc, function(fcy) { 69 | # Preparation 70 | cc <- complete.cases(y, fcy) 71 | y <- y[cc] 72 | fcy <- fcy[cc] 73 | lagycc <- lagy[cc] 74 | n <- sum(cc) 75 | # Undo Bessel's correction: (n-1) instead of n in denominator 76 | nobessel <- sqrt((n - 1) / n) 77 | sdy <- sd(y) * nobessel 78 | sdfcy <- sd(fcy) * nobessel 79 | diff <- fcy - y 80 | # Calculate Measures 81 | bias <- sum(diff) / n # Bias 82 | MSE <- sum(diff^2) / n # Mean Squared Error 83 | BP <- bias^2 / MSE # Bias Proportion 84 | VP <- (sdy - sdfcy)^2 / MSE # Variance Proportion 85 | CP <- 1 - BP - VP # Covariance Proportion 86 | # CP <- 2 * (1 - cor(y, fcy)) * sdy * sdfcy / MSE 87 | RMSE <- sqrt(MSE) # Root MSE 88 | R2 <- 1 - MSE / sdy^2 # R-Squared 89 | SE <- sd(diff) * nobessel # Standard Forecast Error 90 | MAE <- sum(abs(diff)) / n # Mean Absolute Error 91 | MPE <- sum(diff / y) / n * 100 # Mean Percentage Error 92 | MAPE <- sum(abs(diff / y)) / n * 100 # Mean Absolute Percentage Error 93 | U1 <- RMSE / (sqrt(sum(y^2) / n) + sqrt(sum(fcy^2) / n)) # Theils U1 94 | U2 <- sqrt(fmean((diff/lagycc)^2) / fmean((y/lagycc-1)^2)) # Theils U2 95 | # Output 96 | return(c(Bias = bias, MSE = MSE, RMSE = RMSE, `R-Squared` = R2, SE = SE, 97 | MAE = MAE, MPE = MPE, MAPE = MAPE, U1 = U1, U2 = U2, 98 | `Bias Prop.` = BP, `Var. Prop.` = VP, `Cov. Prop.` = CP)) 99 | }, numeric(13)) 100 | attr(res, "naive.added") <- add.naive 101 | attr(res, "n.ahead") <- n.ahead 102 | attr(res, "call") <- match.call() 103 | class(res) <- "eval_forecasts" 104 | return(res) 105 | } 106 | 107 | # Print method 108 | print.eval_forecasts <- function(x, digits = 3, ...) print.table(round(x, digits)) 109 | 110 | # Function to forecast dynamically from a dynamic model (with forecasted predictors) 111 | forecast_dyn <- function(mod, data, y.diff = TRUE) { 112 | miss <- is.na(data) 113 | if(sum(colSums(miss) > 0L) > 1L) stop("Missing values should only be on the dependent variable") 114 | if(any(miss[1L, ])) stop("Missing values at beginning of sample") 115 | data[miss] <- 0 116 | # If the dependent variable is first-differenced in the model ... 117 | if(y.diff) { # .. results at original scale 118 | for(i in which(rowSums(miss) > 0)) { 119 | last <- data[i-1L, miss[i, ]] 120 | data[i, miss[i, ]] <- last + flast(predict(mod, newdata = ss(data, seq_len(i)))) 121 | } 122 | } else { 123 | for(i in which(rowSums(miss) > 0)) 124 | data[i, miss[i, ]] <- flast(predict(mod, newdata = ss(data, seq_len(i)))) 125 | } 126 | data 127 | } -------------------------------------------------------------------------------- /Course 4 - Time Series Analysis and Forecasting in R/resources/Macroeconomic Forecasting with ECM's and DLM's/Macroeconomic Forecasting with ECM and DLM.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SebKrantz/Data-Science-Programme/1f0ea0ea50a940f950b09e684e610aa684756ac6/Course 4 - Time Series Analysis and Forecasting in R/resources/Macroeconomic Forecasting with ECM's and DLM's/Macroeconomic Forecasting with ECM and DLM.pdf -------------------------------------------------------------------------------- /Course 4 - Time Series Analysis and Forecasting in R/resources/Testing for Unit Roots.PNG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SebKrantz/Data-Science-Programme/1f0ea0ea50a940f950b09e684e610aa684756ac6/Course 4 - Time Series Analysis and Forecasting in R/resources/Testing for Unit Roots.PNG -------------------------------------------------------------------------------- /Course 6 - Computable Documents and Interactive Dashboards in R/C6_S2.R: -------------------------------------------------------------------------------- 1 | ############################################################# 2 | # *************** R BASED DATA SCIENCE TRAINING ************* 3 | # Course 6: Computable Documents and Interactive Dashboards 4 | # ----------------------------------------------------------- 5 | # Prepared by: Sebastian Krantz, ODI Fellow, MEPD, MoFPED 6 | # Permanent Contact: sebastian.krantz@graduateinstitute.ch 7 | ############################################################# 8 | 9 | setwd("Course 6 - Computable Documents and Interactive Dashboards in R") 10 | 11 | # (7) Interactive Dashboards with 'flexdashboard' -------------------------- 12 | #*************************************************************************** 13 | 14 | # Dashboards are a useful way to communicate large amounts of information visually and quickly. 15 | # Create one with the flexdashboard::flex_dashboard output format 16 | 17 | install.packages('flexdashboard') 18 | 19 | # Links: 20 | # https://pkgs.rstudio.com/flexdashboard/ 21 | # https://bookdown.org/yihui/rmarkdown/dashboards.html 22 | 23 | 24 | # (8) Case study: Make your own COVID-19 Dashboard ------------------------- 25 | #*************************************************************************** 26 | 27 | # Task: Make a COVID dahboard for Uganda, East Africa or the whole world, including vaccination progress. 28 | # Use interactive visualizations provided by https://www.htmlwidgets.org/ (in particular plotly) 29 | 30 | # COVID Dashboard Example (using plotly for visualization): 31 | # https://github.com/RamiKrispin/coronavirus_dashboard 32 | 33 | # Worldwide Data (Including Vaccination Progress) 34 | install.packages("COVID19") 35 | library(COVID19) 36 | COVID19 <- covid19() # get data for whole world, or for some countries e.g. country == "UGA" 37 | View(COVID19) 38 | 39 | 40 | ### Publishing your Dashboard ---------------------------------------------- 41 | 42 | # Publishing at shinyapps.io (need to make free account and add 'runtime: shiny' to dashboard header), 43 | # then you can publish from Rstudio: 44 | # https://www.shinyapps.io/ 45 | # https://community.rstudio.com/t/how-to-deploy-a-shiny-rmd-file-to-shinyapps-io/30605 46 | # https://community.rstudio.com/t/flexdashboard-publishing/40476 47 | 48 | # Alternatively (for static dashboards which do not need to be updated), you can render the dashboard 49 | # to a simple website using rmarkdown::render, and then publish using github pages: 50 | # https://pages.github.com/ 51 | # https://www.r-bloggers.com/2020/09/deploying-flexdashboard-on-github-pages/ 52 | 53 | 54 | # My COVID Dashboard published at shinyapps.io: 55 | # https://mepd.shinyapps.io/COVID-19/ 56 | -------------------------------------------------------------------------------- /Course 6 - Computable Documents and Interactive Dashboards in R/Computable POE/Computable-POE.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SebKrantz/Data-Science-Programme/1f0ea0ea50a940f950b09e684e610aa684756ac6/Course 6 - Computable Documents and Interactive Dashboards in R/Computable POE/Computable-POE.pdf -------------------------------------------------------------------------------- /Course 6 - Computable Documents and Interactive Dashboards in R/Computable POE/POE-2021-05-MAY-DATA.xlsx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SebKrantz/Data-Science-Programme/1f0ea0ea50a940f950b09e684e610aa684756ac6/Course 6 - Computable Documents and Interactive Dashboards in R/Computable POE/POE-2021-05-MAY-DATA.xlsx -------------------------------------------------------------------------------- /Course 6 - Computable Documents and Interactive Dashboards in R/Computable POE/data/BOU_MMI_frontpage.rds: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SebKrantz/Data-Science-Programme/1f0ea0ea50a940f950b09e684e610aa684756ac6/Course 6 - Computable Documents and Interactive Dashboards in R/Computable POE/data/BOU_MMI_frontpage.rds -------------------------------------------------------------------------------- /Course 6 - Computable Documents and Interactive Dashboards in R/Computable POE/data/POE-other-data.xlsx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SebKrantz/Data-Science-Programme/1f0ea0ea50a940f950b09e684e610aa684756ac6/Course 6 - Computable Documents and Interactive Dashboards in R/Computable POE/data/POE-other-data.xlsx -------------------------------------------------------------------------------- /Course 6 - Computable Documents and Interactive Dashboards in R/Computable POE/images/MDP.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SebKrantz/Data-Science-Programme/1f0ea0ea50a940f950b09e684e610aa684756ac6/Course 6 - Computable Documents and Interactive Dashboards in R/Computable POE/images/MDP.png -------------------------------------------------------------------------------- /Course 6 - Computable Documents and Interactive Dashboards in R/Computable POE/images/MOF_logo_600px_transparent_noborder.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SebKrantz/Data-Science-Programme/1f0ea0ea50a940f950b09e684e610aa684756ac6/Course 6 - Computable Documents and Interactive Dashboards in R/Computable POE/images/MOF_logo_600px_transparent_noborder.png -------------------------------------------------------------------------------- /Course 6 - Computable Documents and Interactive Dashboards in R/Computable POE/images/Monitor.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SebKrantz/Data-Science-Programme/1f0ea0ea50a940f950b09e684e610aa684756ac6/Course 6 - Computable Documents and Interactive Dashboards in R/Computable POE/images/Monitor.png -------------------------------------------------------------------------------- /Course 6 - Computable Documents and Interactive Dashboards in R/Dashboard Example.Rmd: -------------------------------------------------------------------------------- 1 | --- 2 | title: "Untitled" 3 | output: 4 | flexdashboard::flex_dashboard: 5 | theme: yeti 6 | orientation: rows 7 | vertical_layout: fill 8 | css: db.css 9 | 10 | --- 11 | 12 | ```{r setup, include=FALSE} 13 | library(flexdashboard) 14 | library(dygraphs) 15 | library(tsbox) 16 | 17 | 18 | ``` 19 | 20 | Page 1 {data-navmenu="Menu A"} 21 | ===================================== 22 | 23 | Row 24 | ----------------------------------------------------------------------- 25 | 26 | ### Articles per Day 27 | 28 | ```{r} 29 | articles <- 45 30 | valueBox(articles, icon = "fa-pencil") 31 | ``` 32 | 33 | ### Comments per Day 34 | 35 | ```{r} 36 | comments <- 345 37 | valueBox(comments, icon = "fa-comments") 38 | ``` 39 | 40 | ### Spam per Day 41 | 42 | ```{r} 43 | spam <- 10 44 | valueBox(spam, 45 | icon = "fa-trash", 46 | color = ifelse(spam > 10, "warning", "primary")) 47 | ``` 48 | 49 | Row {.tabset .tabset-fade data-width=500} 50 | ----------------------------------------------------------------------- 51 | 52 | ### Chart A 53 | 54 | ```{r} 55 | dygraph(ts_xts(AirPassengers)) 56 | ``` 57 | 58 | ### Table 59 | 60 | ```{r} 61 | DT::datatable(mtcars, options = list( 62 | bPaginate = FALSE 63 | )) 64 | ``` 65 | 66 | 67 | Rows {.tabset .tabset-fade data-width=500} 68 | ----------------------------------------------------------------------- 69 | 70 | ### Chart B 71 | 72 | ```{r} 73 | dygraph(ts_xts(sunspots)) 74 | ``` 75 | 76 | ### Chart C 77 | 78 | ```{r} 79 | dygraph(ts_xts(airmiles)) 80 | ``` 81 | 82 | Page 2 {data-navmenu="Menu A"} 83 | ===================================== 84 | 85 | 86 | Row 87 | ----------------------------------------------------------------------- 88 | 89 | 90 | ### Articles per Day 91 | 92 | ```{r} 93 | articles <- 45 94 | gauge(articles, min = 0, max = 50, gaugeSectors( 95 | success = c(41, 50), warning = c(21, 40), danger = c(0, 20) 96 | )) 97 | ``` 98 | 99 | ### Comments per Day 100 | 101 | ```{r} 102 | comments <- 345 103 | gauge(comments, min = 0, max = 500, gaugeSectors( 104 | success = c(41, 500), warning = c(21, 40), danger = c(0, 20) 105 | )) 106 | ``` 107 | 108 | ### Spam per Day 109 | 110 | ```{r} 111 | spam <- 10 112 | gauge(spam, min = 0, max = 50, gaugeSectors( 113 | success = c(41, 500), warning = c(21, 40), danger = c(0, 20) 114 | )) 115 | ``` 116 | -------------------------------------------------------------------------------- /Course 6 - Computable Documents and Interactive Dashboards in R/HTML/csscheatsheet/css/style.css: -------------------------------------------------------------------------------- 1 | /* 2 | *{ 3 | margin:0; 4 | padding:0; 5 | } 6 | */ 7 | 8 | body{ 9 | background-color:#f4f4f4; 10 | color:#555555; 11 | 12 | font-family: Arial, Helvetica, sans-serif; 13 | font-size:16px; 14 | font-weight:normal; 15 | /* Same as above */ 16 | font: normal 16px Arial, Helvetica, sans-serif; 17 | 18 | line-height:1.6em; 19 | margin:0; 20 | } 21 | 22 | a{ 23 | text-decoration: none; 24 | color:#000; 25 | } 26 | 27 | a:hover{ 28 | color:red; 29 | } 30 | 31 | a:active{ 32 | color:green; 33 | } 34 | 35 | a:visited{ 36 | 37 | } 38 | 39 | .container{ 40 | width:80%; 41 | margin:auto; 42 | } 43 | 44 | .button{ 45 | background-color:#333; 46 | color:#fff; 47 | padding:10px 15px; 48 | border:none; 49 | } 50 | 51 | .button:hover{ 52 | background:red; 53 | color:#fff; 54 | } 55 | 56 | .clr{ 57 | clear:both; 58 | } 59 | 60 | .box-1{ 61 | background-color:#333; 62 | color:#fff; 63 | 64 | border-right:5px red solid; 65 | border-left:5px red solid; 66 | border-top:5px red solid; 67 | border-bottom:5px red solid; 68 | border-width:3px; 69 | border-bottom-width:10px; 70 | border-top-style:dotted; 71 | 72 | border: 5px red solid; 73 | 74 | padding-top:20px; 75 | padding-bottom:20px; 76 | padding-right:20px; 77 | padding-left:20px; 78 | 79 | /* Same as above */ 80 | padding:20px; 81 | 82 | margin-top:20px; 83 | margin:20px 0; 84 | } 85 | 86 | .box-1 h1{ 87 | font-family:Tahoma; 88 | font-weight:800; 89 | font-style:italic; 90 | text-decoration:underline; 91 | text-transform:uppercase; 92 | letter-spacing: 0.2em; 93 | word-spacing: 1em; 94 | } 95 | 96 | .box-2{ 97 | border:3px dotted #ccc; 98 | padding:20px; 99 | margin:20px 0; 100 | } 101 | 102 | .categories{ 103 | border:1px #ccc solid; 104 | padding:10px; 105 | border-radius:15px; 106 | } 107 | 108 | .categories h2{ 109 | text-align:center; 110 | } 111 | 112 | .categories ul{ 113 | padding:0; 114 | padding-left:20px; 115 | list-style:square; 116 | list-style:none; 117 | } 118 | 119 | .categories li{ 120 | padding-bottom:6px; 121 | border-bottom:dotted 1px #333; 122 | list-style-image: url('../images/check.png'); 123 | } 124 | 125 | .my-form{ 126 | padding:20px; 127 | } 128 | 129 | .my-form .form-group{ 130 | padding-bottom:15px; 131 | } 132 | 133 | .my-form label{ 134 | display:block; 135 | } 136 | 137 | .my-form input[type="text"], .my-form textarea{ 138 | padding:8px; 139 | width:100%; 140 | } 141 | 142 | .block{ 143 | float:left; 144 | width:33.3%; 145 | border:1px solid #ccc; 146 | padding:10px; 147 | box-sizing:border-box; 148 | } 149 | 150 | #main-block{ 151 | float:left; 152 | width:70%; 153 | padding:15px; 154 | box-sizing: border-box; 155 | } 156 | 157 | #sidebar{ 158 | float:right; 159 | width:30%; 160 | background-color:#333; 161 | color:#fff; 162 | padding:15px; 163 | box-sizing: border-box; 164 | } 165 | 166 | .p-box{ 167 | width:800px; 168 | height:500px; 169 | border:1px solid #000; 170 | margin-top:30px; 171 | position:relative; 172 | background-image:url('../images/bgimage.jpg'); 173 | background-repeat: no-repeat; 174 | background-position:100px 200px; 175 | background-position:center top; 176 | } 177 | 178 | .p-box h1{ 179 | position:absolute; 180 | top:100px; 181 | left:200px; 182 | } 183 | 184 | .p-box h2{ 185 | position:absolute; 186 | bottom:40px; 187 | right:100px; 188 | } 189 | 190 | .fix-me{ 191 | position:fixed; 192 | top:400px; 193 | } 194 | 195 | .my-list li:first-child{ 196 | background: red; 197 | } 198 | 199 | .my-list li:last-child{ 200 | background: blue; 201 | } 202 | 203 | .my-list li:nth-child(5){ 204 | background: yellow; 205 | } 206 | 207 | .my-list li:nth-child(even){ 208 | background: grey; 209 | } 210 | 211 | -------------------------------------------------------------------------------- /Course 6 - Computable Documents and Interactive Dashboards in R/HTML/csscheatsheet/images/bgimage.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SebKrantz/Data-Science-Programme/1f0ea0ea50a940f950b09e684e610aa684756ac6/Course 6 - Computable Documents and Interactive Dashboards in R/HTML/csscheatsheet/images/bgimage.jpg -------------------------------------------------------------------------------- /Course 6 - Computable Documents and Interactive Dashboards in R/HTML/csscheatsheet/images/check.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SebKrantz/Data-Science-Programme/1f0ea0ea50a940f950b09e684e610aa684756ac6/Course 6 - Computable Documents and Interactive Dashboards in R/HTML/csscheatsheet/images/check.png -------------------------------------------------------------------------------- /Course 6 - Computable Documents and Interactive Dashboards in R/HTML/example-website/css/style.css: -------------------------------------------------------------------------------- 1 | body{ 2 | background-color:#f4f4f4; 3 | color:#555; 4 | font-family:Arial, Helvetica, sans-serif; 5 | font-size:16px; 6 | line-height:1.6em; 7 | margin:0; 8 | } 9 | 10 | .container{ 11 | width:80%; 12 | margin:auto; 13 | overflow:hidden; 14 | } 15 | 16 | #main-header{ 17 | background-color:coral; 18 | color:#fff; 19 | } 20 | 21 | #navbar{ 22 | background-color:#333; 23 | color:#fff; 24 | } 25 | 26 | #navbar ul{ 27 | padding:0; 28 | list-style: none; 29 | } 30 | 31 | #navbar li{ 32 | display:inline; 33 | } 34 | 35 | #navbar a{ 36 | color:#fff; 37 | text-decoration: none; 38 | font-size:18px; 39 | padding-right:15px; 40 | } 41 | 42 | #showcase{ 43 | background-image:url('../images/showcase.jpg'); 44 | background-position:center right; 45 | min-height:300px; 46 | margin-bottom:30px; 47 | text-align: center; 48 | } 49 | 50 | #showcase h1{ 51 | color:#fff; 52 | font-size:50px; 53 | line-height: 1.6em; 54 | padding-top:30px; 55 | } 56 | 57 | #main{ 58 | float:left; 59 | width:70%; 60 | padding:0 30px; 61 | box-sizing: border-box; 62 | } 63 | 64 | #sidebar{ 65 | float:right; 66 | width:30%; 67 | background: #333; 68 | color:#fff; 69 | padding:10px; 70 | box-sizing: border-box; 71 | } 72 | 73 | #main-footer{ 74 | background: #333; 75 | color:#fff; 76 | text-align: center; 77 | padding:20px; 78 | margin-top:40px; 79 | } 80 | 81 | @media(max-width:600px){ 82 | #main{ 83 | width:100%; 84 | float:none; 85 | } 86 | 87 | #sidebar{ 88 | width:100%; 89 | float:none; 90 | } 91 | } -------------------------------------------------------------------------------- /Course 6 - Computable Documents and Interactive Dashboards in R/HTML/example-website/images/showcase.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SebKrantz/Data-Science-Programme/1f0ea0ea50a940f950b09e684e610aa684756ac6/Course 6 - Computable Documents and Interactive Dashboards in R/HTML/example-website/images/showcase.jpg -------------------------------------------------------------------------------- /Course 6 - Computable Documents and Interactive Dashboards in R/HTML/htmlcheatsheet/images/sample.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SebKrantz/Data-Science-Programme/1f0ea0ea50a940f950b09e684e610aa684756ac6/Course 6 - Computable Documents and Interactive Dashboards in R/HTML/htmlcheatsheet/images/sample.jpg -------------------------------------------------------------------------------- /Course 6 - Computable Documents and Interactive Dashboards in R/Latex/GentleLaTeXManual.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SebKrantz/Data-Science-Programme/1f0ea0ea50a940f950b09e684e610aa684756ac6/Course 6 - Computable Documents and Interactive Dashboards in R/Latex/GentleLaTeXManual.pdf -------------------------------------------------------------------------------- /Course 6 - Computable Documents and Interactive Dashboards in R/Latex/LATEX for Beginners.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SebKrantz/Data-Science-Programme/1f0ea0ea50a940f950b09e684e610aa684756ac6/Course 6 - Computable Documents and Interactive Dashboards in R/Latex/LATEX for Beginners.pdf -------------------------------------------------------------------------------- /Course 6 - Computable Documents and Interactive Dashboards in R/Latex/Latex Paper Template/Example Paper - 2 Column Layout + References/israel and the syrian crisis.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SebKrantz/Data-Science-Programme/1f0ea0ea50a940f950b09e684e610aa684756ac6/Course 6 - Computable Documents and Interactive Dashboards in R/Latex/Latex Paper Template/Example Paper - 2 Column Layout + References/israel and the syrian crisis.pdf -------------------------------------------------------------------------------- /Course 6 - Computable Documents and Interactive Dashboards in R/Latex/Latex Paper Template/Latex Paper Template.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SebKrantz/Data-Science-Programme/1f0ea0ea50a940f950b09e684e610aa684756ac6/Course 6 - Computable Documents and Interactive Dashboards in R/Latex/Latex Paper Template/Latex Paper Template.pdf -------------------------------------------------------------------------------- /Course 6 - Computable Documents and Interactive Dashboards in R/Latex/Latex Paper Template/Latex Paper Template.tex: -------------------------------------------------------------------------------- 1 | \documentclass[a4paper, 14pt]{article} 2 | 3 | %% Language and font encodings 4 | \usepackage[english]{babel} % english spellc hecking 5 | \usepackage[utf8x]{inputenc} % whenever you use unicode (non ASCII) characters 6 | \usepackage[T1]{fontenc} % Font encoding: https://tex.stackexchange.com/questions/664/why-should-i-use-usepackaget1fontenc 7 | 8 | % Optionally we can set a different font, such as helvetica neue 9 | % \usepackage[scaled=1]{helvet} 10 | % \renewcommand\familydefault{\sfdefault} 11 | 12 | %% Sets page size and margins 13 | \usepackage[a4paper,top=3cm,bottom=2cm,left=3cm,right=3cm,marginparwidth=1.75cm]{geometry} 14 | 15 | %% Useful packages 16 | \usepackage{amsmath} % Neded for mathematical symbols 17 | \usepackage{graphicx} % Needed for figures 18 | \usepackage{booktabs} % Needed for pretty tables 19 | \usepackage{float} % Fix position of tables and figures using a [H] after \begin{table} and \begin{figure} 20 | \usepackage[colorlinks=true, allcolors=blue]{hyperref} % Make sure links to tables and figures are highlighted in blue 21 | \addto\captionsenglish{\renewcommand*\contentsname{Table of Contents}} % Make sure the table of contents is headed by "Table of Contents" and not just "Contents" 22 | 23 | \title{\textbf{Latex Example Article}} 24 | \author{Sebastian Krantz} 25 | \date{\today} 26 | 27 | \begin{document} 28 | \maketitle 29 | 30 | \begin{abstract} 31 | Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. 32 | \end{abstract} 33 | 34 | \tableofcontents 35 | \listoftables 36 | \listoffigures 37 | 38 | 39 | \newpage %starts new page 40 | 41 | \section{Introduction} 42 | Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo. Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem. Ut enim ad minima veniam, quis nostrum exercitationem ullam corporis suscipit laboriosam, nisi ut aliquid ex ea commodi consequatur? Quis autem vel eum iure reprehenderit qui in ea voluptate velit esse quam nihil molestiae consequatur, vel illum qui dolorem eum fugiat quo voluptas nulla pariatur? 43 | 44 | \section{Section} 45 | \subsection{Subsection} 46 | \subsubsection{Subsubsection} 47 | 48 | \subsection{list} 49 | 50 | \begin{itemize}%Creates lists 51 | \item Item1 52 | \item Item2 53 | \begin{itemize}%Creates list inside list 54 | \item Item21 55 | \item Item22 56 | \item Item23 57 | \end{itemize} 58 | \item Item3 59 | \end{itemize} 60 | 61 | \subsection*{Enumeration} % The * here omits automatic section numbering 62 | 63 | \begin{enumerate}%Creates numbers list 64 | \item Item1 65 | \begin{enumerate} 66 | \item Item1 67 | \item Item2 68 | \end{enumerate} 69 | \item Item2 70 | \end{enumerate} 71 | 72 | some text 73 | 74 | \subsection*{Equations} % The * here omits automatic section numbering 75 | 76 | % Equations 77 | \begin{equation} 78 | e = mc^2 79 | \end{equation} 80 | 81 | \begin{equation} 82 | \underset{y_{kt}}{max}\quad p_t\left(\int_0^{a_t}y_{kt}^{\frac{\psi-1}{\psi}}dk\right)^{\frac{\psi}{\psi-1}}-\int_0^{a_t}p_{kt}y_{kt}dk 83 | \end{equation} 84 | 85 | 86 | We can also write inline math between \$ operators such as $e=mc^2$, or $\Delta y_t = y_t - y_{t-1}$. 87 | 88 | 89 | 90 | \begin{figure}[H] 91 | \centering 92 | \caption{\textsc{Uganda Secondary School and Population Density}} 93 | \label{fig:pl1} 94 | \includegraphics[width=1\textwidth, trim= {0 0 0 0}, clip]{"Schools and Population Choropleth".pdf} %trim={ } 95 | \end{figure} 96 | 97 | Figure \ref{fig:pl1} shows the secondary school and population density in Uganda. 98 | 99 | \newpage %starts new page 100 | \section{Simple Tables} 101 | 102 | Simples table: Left-aligned numbers 103 | \begin{center} %align center 104 | \begin{tabular}{lll} %tables are a bit complicated.you can also put tabular inside an equation 105 | 1 & 2.4545 & 3.1\\ 106 | 4 & 5.35 & 6.545\\ 107 | 7 & 8 & 9\\ 108 | \end{tabular} 109 | \end{center} 110 | 111 | Another table: With borders and different alignment 112 | \begin{center}%align center 113 | \begin{tabular}{|l|c|r|} \hline 114 | 1 & 2 & 3\\ \hline 115 | 4 & 5 & 6\\ 116 | 7 & 8 & 9 \\ 117 | 7 & 8 & 9 \\ \hline 118 | \end{tabular} 119 | \end{center} 120 | 121 | \newpage %starts new page 122 | \section{Publication Quality Tables} 123 | 124 | \begin{table}[H] 125 | \centering 126 | \caption{\textsc{Dependent Variables Predicted}} 127 | \label{tab:DEPPRED} 128 | \vspace{2mm} 129 | \resizebox{1\textwidth}{!}{ %This ensures that the width of the table matches the width of the document (remove for smaller tables that have a width less than the document) 130 | \begin{tabular}{lccccccc} \toprule 131 | \textit{Variables} & \textit{N} & \textit{Mean} & \textit{SD} & \textit{Min} & \textit{Max} & \textit{Skew} & \textit{Kurt} \\ \midrule 132 | GDP per capita PPP, PWT version 6.3 & 1,497 & 2,290 & 2,361 & 154 & 23,444 & 3.38 & 20.6 \\ 133 | GDP per capita growth PPP, PWT version 6.3 & 1,497 & 0.91 & 9.29 & -62.4 & 123 & 2.93 & 38.7 \\ 134 | WDI - GDP per capita growth & 1,393 & 0.96 & 8.40 & -50.2 & 142 & 4.52 & 74.8 \\ 135 | B\&L - Conflict year (25+ battle deaths in current year) & 1,497 & 0.20 & 0.40 & 0 & 1 & 1.51 & 3.29 \\ 136 | LAN - UCDP Non-State Conflict & 834 & 0.32 & 0.96 & 0 & 8 & 4.06 & 22.3 \\ 137 | B\&L - Onset (>25 death) after >2 years of peace & 1,497 & 0.043 & 0.20 & 0 & 1 & 4.52 & 21.4 \\ 138 | KOB - Civil Conflict Onset (>25 deaths) after >9 years of peace & 1,317 & 0.029 & 0.17 & 0 & 1 & 5.63 & 32.7 \\ 139 | KOB - Conflict onset (>1000 deaths) after >9 years of peace & 1,317 & 0.012 & 0.11 & 0 & 1 & 8.91 & 80.3 \\ 140 | BBST - PRIO battle deaths best estimate & 1,497 & 577 & 2,834 & 0 & 36,250 & 8.63 & 91.3 \\ \bottomrule 141 | \end{tabular} 142 | } 143 | \end{table} 144 | 145 | 146 | Table \ref{tab:DEPPRED} shows summary satistics of various indicators. 147 | 148 | \end{document} -------------------------------------------------------------------------------- /Course 6 - Computable Documents and Interactive Dashboards in R/Latex/Latex Paper Template/Schools and Population Choropleth.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SebKrantz/Data-Science-Programme/1f0ea0ea50a940f950b09e684e610aa684756ac6/Course 6 - Computable Documents and Interactive Dashboards in R/Latex/Latex Paper Template/Schools and Population Choropleth.pdf -------------------------------------------------------------------------------- /Course 6 - Computable Documents and Interactive Dashboards in R/Latex/Latex Presentation Template/Another Presentation/Dissertation Presentation.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SebKrantz/Data-Science-Programme/1f0ea0ea50a940f950b09e684e610aa684756ac6/Course 6 - Computable Documents and Interactive Dashboards in R/Latex/Latex Presentation Template/Another Presentation/Dissertation Presentation.pdf -------------------------------------------------------------------------------- /Course 6 - Computable Documents and Interactive Dashboards in R/Latex/Latex Presentation Template/Example Presentation/Figures/Fig1.PNG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SebKrantz/Data-Science-Programme/1f0ea0ea50a940f950b09e684e610aa684756ac6/Course 6 - Computable Documents and Interactive Dashboards in R/Latex/Latex Presentation Template/Example Presentation/Figures/Fig1.PNG -------------------------------------------------------------------------------- /Course 6 - Computable Documents and Interactive Dashboards in R/Latex/Latex Presentation Template/Example Presentation/Figures/Fig2.PNG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SebKrantz/Data-Science-Programme/1f0ea0ea50a940f950b09e684e610aa684756ac6/Course 6 - Computable Documents and Interactive Dashboards in R/Latex/Latex Presentation Template/Example Presentation/Figures/Fig2.PNG -------------------------------------------------------------------------------- /Course 6 - Computable Documents and Interactive Dashboards in R/Latex/Latex Presentation Template/Example Presentation/Figures/Fig22.PNG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SebKrantz/Data-Science-Programme/1f0ea0ea50a940f950b09e684e610aa684756ac6/Course 6 - Computable Documents and Interactive Dashboards in R/Latex/Latex Presentation Template/Example Presentation/Figures/Fig22.PNG -------------------------------------------------------------------------------- /Course 6 - Computable Documents and Interactive Dashboards in R/Latex/Latex Presentation Template/Example Presentation/Figures/Fig3.PNG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SebKrantz/Data-Science-Programme/1f0ea0ea50a940f950b09e684e610aa684756ac6/Course 6 - Computable Documents and Interactive Dashboards in R/Latex/Latex Presentation Template/Example Presentation/Figures/Fig3.PNG -------------------------------------------------------------------------------- /Course 6 - Computable Documents and Interactive Dashboards in R/Latex/Latex Presentation Template/Example Presentation/Figures/Fig31.PNG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SebKrantz/Data-Science-Programme/1f0ea0ea50a940f950b09e684e610aa684756ac6/Course 6 - Computable Documents and Interactive Dashboards in R/Latex/Latex Presentation Template/Example Presentation/Figures/Fig31.PNG -------------------------------------------------------------------------------- /Course 6 - Computable Documents and Interactive Dashboards in R/Latex/Latex Presentation Template/Example Presentation/Figures/Fig33.PNG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SebKrantz/Data-Science-Programme/1f0ea0ea50a940f950b09e684e610aa684756ac6/Course 6 - Computable Documents and Interactive Dashboards in R/Latex/Latex Presentation Template/Example Presentation/Figures/Fig33.PNG -------------------------------------------------------------------------------- /Course 6 - Computable Documents and Interactive Dashboards in R/Latex/Latex Presentation Template/Example Presentation/Figures/Fig4.PNG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SebKrantz/Data-Science-Programme/1f0ea0ea50a940f950b09e684e610aa684756ac6/Course 6 - Computable Documents and Interactive Dashboards in R/Latex/Latex Presentation Template/Example Presentation/Figures/Fig4.PNG -------------------------------------------------------------------------------- /Course 6 - Computable Documents and Interactive Dashboards in R/Latex/Latex Presentation Template/Example Presentation/Figures/Fig41.PNG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SebKrantz/Data-Science-Programme/1f0ea0ea50a940f950b09e684e610aa684756ac6/Course 6 - Computable Documents and Interactive Dashboards in R/Latex/Latex Presentation Template/Example Presentation/Figures/Fig41.PNG -------------------------------------------------------------------------------- /Course 6 - Computable Documents and Interactive Dashboards in R/Latex/Latex Presentation Template/Example Presentation/Figures/Fig44.PNG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SebKrantz/Data-Science-Programme/1f0ea0ea50a940f950b09e684e610aa684756ac6/Course 6 - Computable Documents and Interactive Dashboards in R/Latex/Latex Presentation Template/Example Presentation/Figures/Fig44.PNG -------------------------------------------------------------------------------- /Course 6 - Computable Documents and Interactive Dashboards in R/Latex/Latex Presentation Template/Example Presentation/Figures/FigB12.PNG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SebKrantz/Data-Science-Programme/1f0ea0ea50a940f950b09e684e610aa684756ac6/Course 6 - Computable Documents and Interactive Dashboards in R/Latex/Latex Presentation Template/Example Presentation/Figures/FigB12.PNG -------------------------------------------------------------------------------- /Course 6 - Computable Documents and Interactive Dashboards in R/Latex/Latex Presentation Template/Example Presentation/Figures/FigB6.PNG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SebKrantz/Data-Science-Programme/1f0ea0ea50a940f950b09e684e610aa684756ac6/Course 6 - Computable Documents and Interactive Dashboards in R/Latex/Latex Presentation Template/Example Presentation/Figures/FigB6.PNG -------------------------------------------------------------------------------- /Course 6 - Computable Documents and Interactive Dashboards in R/Latex/Latex Presentation Template/Example Presentation/Figures/Site.PNG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SebKrantz/Data-Science-Programme/1f0ea0ea50a940f950b09e684e610aa684756ac6/Course 6 - Computable Documents and Interactive Dashboards in R/Latex/Latex Presentation Template/Example Presentation/Figures/Site.PNG -------------------------------------------------------------------------------- /Course 6 - Computable Documents and Interactive Dashboards in R/Latex/Latex Presentation Template/Example Presentation/Figures/Site2.PNG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SebKrantz/Data-Science-Programme/1f0ea0ea50a940f950b09e684e610aa684756ac6/Course 6 - Computable Documents and Interactive Dashboards in R/Latex/Latex Presentation Template/Example Presentation/Figures/Site2.PNG -------------------------------------------------------------------------------- /Course 6 - Computable Documents and Interactive Dashboards in R/Latex/Latex Presentation Template/Example Presentation/Figures/Tab1.PNG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SebKrantz/Data-Science-Programme/1f0ea0ea50a940f950b09e684e610aa684756ac6/Course 6 - Computable Documents and Interactive Dashboards in R/Latex/Latex Presentation Template/Example Presentation/Figures/Tab1.PNG -------------------------------------------------------------------------------- /Course 6 - Computable Documents and Interactive Dashboards in R/Latex/Latex Presentation Template/Example Presentation/Figures/Tab11.PNG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SebKrantz/Data-Science-Programme/1f0ea0ea50a940f950b09e684e610aa684756ac6/Course 6 - Computable Documents and Interactive Dashboards in R/Latex/Latex Presentation Template/Example Presentation/Figures/Tab11.PNG -------------------------------------------------------------------------------- /Course 6 - Computable Documents and Interactive Dashboards in R/Latex/Latex Presentation Template/Example Presentation/Figures/Tab2.PNG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SebKrantz/Data-Science-Programme/1f0ea0ea50a940f950b09e684e610aa684756ac6/Course 6 - Computable Documents and Interactive Dashboards in R/Latex/Latex Presentation Template/Example Presentation/Figures/Tab2.PNG -------------------------------------------------------------------------------- /Course 6 - Computable Documents and Interactive Dashboards in R/Latex/Latex Presentation Template/Example Presentation/Figures/Tab3.PNG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SebKrantz/Data-Science-Programme/1f0ea0ea50a940f950b09e684e610aa684756ac6/Course 6 - Computable Documents and Interactive Dashboards in R/Latex/Latex Presentation Template/Example Presentation/Figures/Tab3.PNG -------------------------------------------------------------------------------- /Course 6 - Computable Documents and Interactive Dashboards in R/Latex/Latex Presentation Template/Example Presentation/Figures/Tab4.PNG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SebKrantz/Data-Science-Programme/1f0ea0ea50a940f950b09e684e610aa684756ac6/Course 6 - Computable Documents and Interactive Dashboards in R/Latex/Latex Presentation Template/Example Presentation/Figures/Tab4.PNG -------------------------------------------------------------------------------- /Course 6 - Computable Documents and Interactive Dashboards in R/Latex/Latex Presentation Template/Example Presentation/Figures/Tab5.PNG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SebKrantz/Data-Science-Programme/1f0ea0ea50a940f950b09e684e610aa684756ac6/Course 6 - Computable Documents and Interactive Dashboards in R/Latex/Latex Presentation Template/Example Presentation/Figures/Tab5.PNG -------------------------------------------------------------------------------- /Course 6 - Computable Documents and Interactive Dashboards in R/Latex/Latex Presentation Template/Example Presentation/Lee, Miguel & Wolfram (2018).pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SebKrantz/Data-Science-Programme/1f0ea0ea50a940f950b09e684e610aa684756ac6/Course 6 - Computable Documents and Interactive Dashboards in R/Latex/Latex Presentation Template/Example Presentation/Lee, Miguel & Wolfram (2018).pdf -------------------------------------------------------------------------------- /Course 6 - Computable Documents and Interactive Dashboards in R/Latex/Latex Presentation Template/Latex Presentation Template (Beamer).pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SebKrantz/Data-Science-Programme/1f0ea0ea50a940f950b09e684e610aa684756ac6/Course 6 - Computable Documents and Interactive Dashboards in R/Latex/Latex Presentation Template/Latex Presentation Template (Beamer).pdf -------------------------------------------------------------------------------- /Course 6 - Computable Documents and Interactive Dashboards in R/Latex/Latex Presentation Template/Latex Presentation Template (Beamer).tex: -------------------------------------------------------------------------------- 1 | % Use Beamer class, with extended Latex colours 2 | \documentclass[compress,xcolor=dvipsnames]{beamer} 3 | 4 | % Use miniframes: Small circles at the top telling you where you are in the presentation 5 | \useoutertheme[subsection=false]{miniframes} % No miniframes for subsections 6 | \setbeamercolor{mini frame}{fg=NavyBlue,bg=NavyBlue} % https://tex.stackexchange.com/questions/228256/control-colors-and-shading-of-navigation-circles-in-beamer-top-line 7 | \setbeamerfont{headline}{size=\tiny} % Headline font size 8 | \useinnertheme{circles}% http://blogs.ubc.ca/khead/research/research-advice/better-beamer-presentations 9 | 10 | % https://tex.stackexchange.com/questions/44983/beamer-removing-headline-and-its-space-on-a-single-frame-for-plan-but-keepin : 11 | \makeatletter 12 | \newenvironment{noheadline}{ 13 | \setbeamertemplate{headline}{} 14 | \addtobeamertemplate{frametitle}{\vspace*{-0.9\baselineskip}}{} 15 | }{} 16 | \makeatother 17 | 18 | % Appearance and colours 19 | % Available colours: https://www.overleaf.com/learn/latex/Using_colours_in_LaTeX 20 | % You can also define custom colours: https://martin-thoma.com/colors-in-latex/ 21 | \mode { 22 | \setbeamertemplate{caption}[numbeNavyBlue] 23 | \setbeamercolor{section number projected}{bg=Red,fg=white} % https://tex.stackexchange.com/questions/8011/changing-color-and-bullets-in-beamers-table-of-contents 24 | \setbeamertemplate{navigation symbols}{} % Swith off naviagation symbols: https://nickhigham.wordpress.com/2013/01/18/top-5-beamer-tips/ 25 | \setbeamercolor{frametitle}{fg=NavyBlue!140} 26 | \setbeamercolor{title}{fg=Cerulean} 27 | \setbeamercolor{normal text}{fg=black!85} 28 | \setbeamercolor{enumerate item}{fg=NavyBlue!140} 29 | \setbeamercolor{enumerate subitem}{fg=NavyBlue!140} 30 | \setbeamercolor{enumerate subsubitem}{fg=NavyBlue!140} 31 | \setbeamercolor{caption name}{fg=NavyBlue} 32 | \setbeamercolor{itemize item}{fg=NavyBlue!140} 33 | \setbeamercolor{itemize subitem}{fg=NavyBlue!140} 34 | \setbeamercolor{itemize subsubitem}{fg=NavyBlue!140} 35 | \setbeamercolor{section in toc}{fg=NavyBlue!140} 36 | \setbeamercolor{subsection in toc}{fg=NavyBlue!120} 37 | \setbeamercolor{footlinecolor0}{fg=white,bg=NavyBlue!140} 38 | \setbeamercolor{footlinecolor1}{fg=white,bg=NavyBlue} 39 | \setbeamercolor{footlinecolor2}{fg=black,bg=NavyBlue!60} 40 | 41 | % Footline 42 | \setbeamertemplate{footline} 43 | { 44 | \leavevmode% 45 | \hbox{% 46 | \begin{beamercolorbox}[wd=.3\paperwidth,ht=2.25ex,dp=1ex,center]{footlinecolor0} 47 | Sebastian Krantz (IHEID) %\insertsectionhead 48 | \end{beamercolorbox}% 49 | \begin{beamercolorbox}[wd=.3\paperwidth,ht=2.25ex,dp=1ex,center]{footlinecolor1} 50 | Authors %\insertsectionhead 51 | \end{beamercolorbox}% 52 | \begin{beamercolorbox}[wd=.4\paperwidth,ht=2.25ex,dp=1ex,right]{footlinecolor2}% center 53 | \insertshorttitle\hspace*{2em} % 3em 54 | \insertframenumber{} / \inserttotalframenumber\hspace*{1ex} 55 | \end{beamercolorbox}}% 56 | } 57 | 58 | 59 | % Language and font encodings 60 | \usepackage[english]{babel} 61 | \usepackage[utf8x]{inputenc} 62 | \usepackage[T1]{fontenc} 63 | 64 | % Other useful packages 65 | \usepackage{amsmath} % Allows mathematics 66 | \usepackage{graphicx} % Allows including images 67 | \usepackage{booktabs} % Allows the use of \toprule, \midrule and \bottomrule in tables for pretty formatting 68 | \usepackage{float} % Allows fixing the position of tables and figures using H 69 | \usepackage{enumitem}% Allows enumeration lists 70 | \setitemize{label=\textbullet, font=\large \color{Red}, itemsep=12pt} % https://stackoverflow.com/questions/4968557/latex-very-compact-itemize 71 | 72 | 73 | } 74 | 75 | %---------------------------------------------------------------------------------------- 76 | % TITLE PAGE 77 | %---------------------------------------------------------------------------------------- 78 | \title[Short Title]{\textbf{Main Title}} % The short title appears at the bottom of every slide, the full title is only on the title page 79 | 80 | \author{Author} % Your name 81 | \institute[The Graduate Institute] 82 | { 83 | Presented by Sebastian Krantz, \\ \vspace{2mm} Geneva Graduate Institute\\ % Your institution for the title page 84 | \bigskip 85 | %{\large International Conference on Capital Flows and Safe Assets} % Conference Name (optional) 86 | } 87 | \date{\today} % Date, can be changed to a custom date 88 | 89 | \begin{document} 90 | 91 | \begin{noheadline} 92 | \begin{frame} 93 | \titlepage 94 | \end{frame} 95 | 96 | %---------------------------------------------------------------------------------------- 97 | % PRESENTATION SLIDES 98 | %---------------------------------------------------------------------------------------- 99 | 100 | \begin{frame} 101 | \frametitle{Table of Contents} 102 | \tableofcontents 103 | \end{frame} 104 | 105 | 106 | %------------------------------------------------ 107 | \section{Introduction} 108 | %------------------------------------------------ 109 | 110 | \begin{frame} 111 | \frametitle{Introduction} 112 | \begin{itemize} 113 | \item 114 | \end{itemize} 115 | \end{frame} 116 | \end{noheadline} 117 | 118 | \begin{frame} 119 | \begin{itemize} 120 | \item 121 | \end{itemize} 122 | \end{frame} 123 | 124 | 125 | \end{document} 126 | -------------------------------------------------------------------------------- /Course 6 - Computable Documents and Interactive Dashboards in R/Latex/Not so Short Introduction to LATEX.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SebKrantz/Data-Science-Programme/1f0ea0ea50a940f950b09e684e610aa684756ac6/Course 6 - Computable Documents and Interactive Dashboards in R/Latex/Not so Short Introduction to LATEX.pdf -------------------------------------------------------------------------------- /Course 6 - Computable Documents and Interactive Dashboards in R/Latex/a-quick-guide-to-latex.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SebKrantz/Data-Science-Programme/1f0ea0ea50a940f950b09e684e610aa684756ac6/Course 6 - Computable Documents and Interactive Dashboards in R/Latex/a-quick-guide-to-latex.pdf -------------------------------------------------------------------------------- /Course 6 - Computable Documents and Interactive Dashboards in R/Latex/fiscal.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SebKrantz/Data-Science-Programme/1f0ea0ea50a940f950b09e684e610aa684756ac6/Course 6 - Computable Documents and Interactive Dashboards in R/Latex/fiscal.pdf -------------------------------------------------------------------------------- /Course 6 - Computable Documents and Interactive Dashboards in R/Latex/fiscal.tex: -------------------------------------------------------------------------------- 1 | \documentclass[a4paper]{article} 2 | 3 | %% Language and font encodings 4 | \usepackage[english]{babel} 5 | \usepackage[utf8x]{inputenc} 6 | \usepackage[T1]{fontenc} 7 | 8 | %% Sets page size and margins 9 | \usepackage[a4paper,top=3cm,bottom=2cm,left=3cm,right=3cm,marginparwidth=1.75cm]{geometry} 10 | 11 | %% Useful packages 12 | \usepackage{amsmath} 13 | \usepackage{graphicx} 14 | \usepackage[colorinlistoftodos]{todonotes} 15 | \usepackage[colorlinks=true, allcolors=blue]{hyperref} 16 | %\usepackage{apacite} 17 | %\AtBeginDocument{\urlstyle{APACsame}} 18 | %\usepackage[section]{placeins} 19 | %\usepackage{hyperref} 20 | %\usepackage{multirow} 21 | \usepackage{tabulary} 22 | \usepackage{adjustbox} 23 | \usepackage{mathtools} 24 | %\usepackage{natbib} 25 | \usepackage{booktabs} 26 | %\usepackage{array} 27 | %\usepackage{tablefootnote} 28 | %\usepackage{threeparttable} 29 | %\usepackage{xcolor} 30 | %\addto\captionsenglish{\renewcommand*\contentsname{Table of Contents}} 31 | 32 | 33 | \title{\textbf{...}} 34 | \author{Sebastian Krantz} 35 | 36 | \begin{document} 37 | \maketitle 38 | 39 | % Please add the following required packages to your document preamble: 40 | % \usepackage{booktabs} 41 | \begin{table}[] 42 | \begin{tabular}{@{}lrrrr@{}} 43 | \toprule 44 | \textbf{Shs Billion} & \textbf{Program} & \textbf{Outturn} & \textbf{Performance} & \textbf{Deviation} \\ \midrule 45 | \textbf{Revenues and grants} & \textbf{1759.99} & \textbf{1621.76} & \textbf{0.92146} & \textbf{-138.23} \\ \midrule 46 | Revenues & 1577.15 & 1609.67 & 1.020619 & 32.52 \\ 47 | Tax & 1440.1 & 1521.15 & 1.056281 & 81.05 \\ 48 | Non-tax & 137.05 & 88.52 & 0.645896 & -48.53 \\ 49 | \hspace{1cm} Grants & 182.85 & 12.09 & 0.06612 & -170.76 \\ 50 | \multicolumn{2}{l}{Budget support} & & - & 0 \\ 51 | o/w HIPC debt relief & & & - & 0 \\ 52 | o/w Project support & & & - & 0 \\ \midrule 53 | \textbf{Expenditures and lending} & \textbf{2568.01} & \textbf{2897.46} & \textbf{1.12829} & \textbf{329.45} \\ 54 | Current expenditures & 1179.01 & 1575.95 & 1.336672 & 396.94 \\ 55 | Wages and salaries & 406.6 & 411.61 & 1.012322 & 5.01 \\ 56 | Interest payments & 336.92 & 330.16 & 0.979936 & -6.76 \\ 57 | o/w domestic & 262.9 & 262.95 & 1.00019 & 0.05 \\ 58 | o/w external & 74 & 67.21 & 0.908243 & -6.79 \\ 59 | Other recurrent expenditure & 435.5 & 834.18 & 1.915454 & 398.68 \\ 60 | Development expenditures & 1382.65 & 1305.89 & 0.944483 & -76.76 \\ 61 | Domestic & 694.7 & 1235.79 & 1.778883 & 541.09 \\ 62 | External & 688 & 70.1 & 0.10189 & -617.9 \\ 63 | \multicolumn{2}{l}{Net lending/repayments} & 11.32 & - & 11.32 \\ 64 | \multicolumn{2}{l}{o/w HPP GoU} & 11.32 & - & 11.32 \\ 65 | \multicolumn{2}{l}{HPP Exim} & & - & 0 \\ 66 | Domestic arrears repayment & 6.3 & 4.3 & 0.68254 & -2 \\ \midrule 67 | \textbf{Domestic fiscal balance} & \textbf{-808.01} & \textbf{-1275.69} & \textbf{} & \textbf{} \\ \bottomrule 68 | \end{tabular} 69 | \end{table} 70 | 71 | \end{document} -------------------------------------------------------------------------------- /Course 6 - Computable Documents and Interactive Dashboards in R/Latex/guide-tables.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SebKrantz/Data-Science-Programme/1f0ea0ea50a940f950b09e684e610aa684756ac6/Course 6 - Computable Documents and Interactive Dashboards in R/Latex/guide-tables.pdf -------------------------------------------------------------------------------- /Course 6 - Computable Documents and Interactive Dashboards in R/UGACAB.Rmd: -------------------------------------------------------------------------------- 1 | --- 2 | title: "Current Account and Balance of Trade" 3 | author: "Sebastian Krantz" 4 | date: "6/24/2021" 5 | output: 6 | html_document: 7 | theme: cerulean 8 | toc: true 9 | toc_float: true 10 | --- 11 | 12 | ```{r setup, include=FALSE} 13 | knitr::opts_chunk$set(echo = FALSE, message = FALSE, warning = FALSE, cache = TRUE) 14 | 15 | ``` 16 | 17 | ```{css} 18 | /* 19 | body{ 20 | background-color: #959a9c; 21 | } 22 | 23 | h2{ 24 | font-weight: bold; 25 | } 26 | */ 27 | ``` 28 | 29 | ```{r, data, include=FALSE} 30 | library(ugatsdb) 31 | ugatsdb_reconnect() 32 | bop_data <- get_data("BOU_BOP", c("CAB", "CA_G")) 33 | names(bop_data)[-1] <- c("Current Account", "Balance of Trade") 34 | ``` 35 | 36 | ```{r constants, include=FALSE} 37 | mean_CAB <- mean(bop_data$`Current Account`) 38 | mean_TB <- mean(bop_data$`Balance of Trade`) 39 | 40 | text <- if(mean_CAB > mean_TB) "higher" else "lower" 41 | ``` 42 | 43 | ## A Static Plot 44 | 45 | The plot below shows the quarterly **current account balance** and **balance of trade for Uganda**. 46 | The average CAB over the period has been **`r round(mean_CAB)`** whereas the average trade balance has been **`r round(mean_TB)`**. Thus on average the CAB has been `r if(mean_CAB > mean_TB) "higher" else "lower"` than the TB. 47 | 48 | ```{r static} 49 | library(xts) 50 | bop_xts <- as.xts(bop_data) 51 | plot(bop_xts, legend.loc = "topright", 52 | main = "Current account and balance of trade", 53 | yaxis.right = FALSE) 54 | 55 | ``` 56 | 57 | You can see that both move together very closely. We can observe: 58 | 59 | * CAB is initially a lot higher than TB 60 | * CAB deteriorates and is about equal to TB in 2010 61 | + Yet the CAB is more volatile than the TB 62 | 63 | ## A Dynamic Plot 64 | 65 | This shows a dynamic plot of the same thing. 66 | 67 | ```{r dynamic} 68 | library(dygraphs) 69 | dygraph(bop_xts) 70 | ``` 71 | 72 | ### A table 73 | 74 | ```{r, results='asis'} 75 | 76 | knitr::kable(tail(bop_data)) 77 | ``` 78 | 79 | 80 | -------------------------------------------------------------------------------- /Course 6 - Computable Documents and Interactive Dashboards in R/Uganda-Covid.Rmd: -------------------------------------------------------------------------------- 1 | --- 2 | title: "COVID-Uganda" 3 | author: "Sebastian Krantz" 4 | date: "6/24/2021" 5 | output: beamer_presentation 6 | 7 | header-includes: 8 | \usepackage{booktabs} 9 | --- 10 | 11 | ```{r setup, include=FALSE} 12 | knitr::opts_chunk$set(echo = FALSE) 13 | ``` 14 | 15 | ```{r data, include=FALSE} 16 | ugatsdb::ugatsdb_reconnect() 17 | data <- ugatsdb::get_data("MOF_POE", c("CIEA", "BTI", "PMI", "EX", "IM", "TB"), from = 2019) 18 | data_xts <- xts::as.xts(data) 19 | library(collapse) 20 | lab <- vlabels(data) 21 | ``` 22 | 23 | ## Indicators 24 | 25 | The impact of the COVID pandemic on Uganda can be seen through the following indicators. 26 | 27 | ```{r table} 28 | library(kableExtra) 29 | library(magrittr) 30 | qsu(data, cols = -1, vlabels = TRUE) %>% 31 | round(2) %>% 32 | kbl(format = "latex", booktabs = TRUE, linesep = "", 33 | caption = "Key Economic Indicators") %>% 34 | kable_styling(latex_options = "scale_down") 35 | ``` 36 | 37 | **PMI** and **BTI** are indices with a threshold at 50, below which economic 38 | activity is considered to be low. The **CIEA** is an index composed of increasing variables. 39 | 40 | ## Composite Index of Economic Activity 41 | 42 | - The **CIEA** shows a sharp drop between February and July 2020, when Uganda had the first lockdown. 43 | 44 | ```{r} 45 | plot(data_xts[, "CIEA"], col = "orange", main = lab["CIEA"]) 46 | ``` 47 | 48 | ## Business Tendency Indicator 49 | 50 | - The **BTI** shows a sharp drop in Fbruary 2020, and has not quite recovered yet in spring 2021. 51 | 52 | ```{r} 53 | plot(data_xts[, "BTI"], col = "darkgreen", main = lab["BTI"]) 54 | ``` 55 | 56 | ## Purchasing Managers Index 57 | 58 | - The **PMI** shows a sharp drop in between February and September 2020. 59 | 60 | ```{r} 61 | plot(data_xts[, "PMI"], col = "magenta", main = lab["PMI"]) 62 | ``` 63 | 64 | ## Exports and Imports 65 | 66 | - Exports and Imports declined between May and August 2020. 67 | 68 | ```{r} 69 | plot(data_xts[, c("EX", "IM")], main = "Exports and Imports (US$ millions)", legend.loc = "topleft") 70 | ``` 71 | 72 | ## Balance of Trade 73 | 74 | - The trade balance has improved slightly suring the lockdown, as other countries did not have such a stringent lockdown. 75 | 76 | ```{r} 77 | plot(data_xts[, "TB"], col = "red", main = lab["TB"]) 78 | ``` 79 | 80 | ## Conclusion 81 | 82 | - COVID-19 and the first lockdown between March 2020 and July 2020 had a profound impact on the Ugandan economy. 83 | -------------------------------------------------------------------------------- /Course 6 - Computable Documents and Interactive Dashboards in R/Uganda-Covid.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SebKrantz/Data-Science-Programme/1f0ea0ea50a940f950b09e684e610aa684756ac6/Course 6 - Computable Documents and Interactive Dashboards in R/Uganda-Covid.pdf -------------------------------------------------------------------------------- /Course 6 - Computable Documents and Interactive Dashboards in R/db.css: -------------------------------------------------------------------------------- 1 | .navbar-inverse { 2 | background-color: rgb(19, 42, 49); 3 | } 4 | 5 | .nav-tabs-custom > .nav-tabs { 6 | margin: 0; 7 | border-bottom: 1px solid #d7d7d7; 8 | color: #a28787; 9 | font-size: 14px; 10 | font-weight: 300; 11 | border-top-right-radius: 3px; 12 | border-top-left-radius: 3px; 13 | background-color: #006687; 14 | } -------------------------------------------------------------------------------- /Course 6 - Computable Documents and Interactive Dashboards in R/fiscal.Rmd: -------------------------------------------------------------------------------- 1 | --- 2 | title: "Fiscal" 3 | author: "Sebastian Krantz" 4 | date: "6/25/2021" 5 | output: pdf_document 6 | --- 7 | 8 | ```{r setup, include=FALSE} 9 | knitr::opts_chunk$set(echo = TRUE) 10 | ``` 11 | 12 | 13 | ```{r fiscal, results='asis'} 14 | library(readxl) 15 | library(kableExtra) 16 | library(collapse) 17 | library(magrittr) 18 | fiscal <- read_excel("Computable POE/data/POE-other-data.xlsx") 19 | settransformv(fiscal, -1, as.numeric) 20 | settransformv(fiscal, 4, scales::percent) 21 | 22 | kbl(fiscal, format = "latex", booktabs = TRUE, linesep = '') %>% 23 | kable_classic() %>% 24 | row_spec(1, hline_after = TRUE) %>% 25 | row_spec(c(8, 22), hline_after = TRUE) %>% 26 | row_spec(c(1,9,23), bold = TRUE) 27 | 28 | ``` 29 | 30 | -------------------------------------------------------------------------------- /Course 6 - Computable Documents and Interactive Dashboards in R/fiscal.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SebKrantz/Data-Science-Programme/1f0ea0ea50a940f950b09e684e610aa684756ac6/Course 6 - Computable Documents and Interactive Dashboards in R/fiscal.pdf -------------------------------------------------------------------------------- /Course 7 - Web-Applications with Shiny in R/Example Apps/app1/app.R: -------------------------------------------------------------------------------- 1 | library(shiny) 2 | 3 | # Define UI for app that draws a histogram ---- 4 | ui <- fluidPage( 5 | 6 | # App title ---- 7 | titlePanel("Hello World!"), 8 | 9 | # Sidebar layout with input and output definitions ---- 10 | sidebarLayout( 11 | 12 | # Sidebar panel for inputs ---- 13 | sidebarPanel( 14 | 15 | # Input: Slider for the number of bins ---- 16 | sliderInput(inputId = "bins", 17 | label = "Number of bins:", 18 | min = 5, 19 | max = 50, 20 | value = 30) 21 | 22 | ), 23 | 24 | # Main panel for displaying outputs ---- 25 | mainPanel( 26 | 27 | # Output: Histogram ---- 28 | plotOutput(outputId = "distPlot") 29 | 30 | ) 31 | ) 32 | ) 33 | 34 | # Define server logic required to draw a histogram ---- 35 | server <- function(input, output) { 36 | 37 | # Histogram of the Old Faithful Geyser Data ---- 38 | # with requested number of bins 39 | # This expression that generates a histogram is wrapped in a call 40 | # to renderPlot to indicate that: 41 | # 42 | # 1. It is "reactive" and therefore should be automatically 43 | # re-executed when inputs (input$bins) change 44 | # 2. Its output type is a plot 45 | output$distPlot <- renderPlot({ 46 | 47 | x <- faithful$waiting 48 | bins <- seq(min(x), max(x), length.out = input$bins + 1) 49 | 50 | hist(x, breaks = bins, col = "#75AADB", border = "orange", 51 | xlab = "Waiting time to next eruption (in mins)", 52 | main = "Histogram of waiting times") 53 | 54 | }) 55 | 56 | } 57 | 58 | # Create Shiny app ---- 59 | shinyApp(ui = ui, server = server) -------------------------------------------------------------------------------- /Course 7 - Web-Applications with Shiny in R/Example Apps/app1/app_1_server.R: -------------------------------------------------------------------------------- 1 | # Define server logic required to draw a histogram ---- 2 | server <- function(input, output) { 3 | 4 | # Histogram of the Old Faithful Geyser Data ---- 5 | # with requested number of bins 6 | # This expression that generates a histogram is wrapped in a call 7 | # to renderPlot to indicate that: 8 | # 9 | # 1. It is "reactive" and therefore should be automatically 10 | # re-executed when inputs (input$bins) change 11 | # 2. Its output type is a plot 12 | output$distPlot <- renderPlot({ 13 | 14 | x <- faithful$waiting 15 | bins <- seq(min(x), max(x), length.out = input$bins + 1) 16 | 17 | hist(x, breaks = bins, col = "#75AADB", border = "white", 18 | xlab = "Waiting time to next eruption (in mins)", 19 | main = "Histogram of waiting times") 20 | 21 | }) 22 | 23 | } -------------------------------------------------------------------------------- /Course 7 - Web-Applications with Shiny in R/Example Apps/app2/app.R: -------------------------------------------------------------------------------- 1 | library(shiny) 2 | 3 | # Define UI ---- 4 | ui <- fluidPage( 5 | titlePanel("My Star Wars App"), 6 | 7 | sidebarLayout(position = "right", 8 | sidebarPanel("sidebar panel"), 9 | mainPanel( 10 | img(src = "rstudio.png", height = 140, width = 400), 11 | h6("Episode IV", align = "center"), 12 | h6("A NEW HOPE", align = "center"), 13 | h5("It is a period of civil war.", align = "center"), 14 | h4("Rebel spaceships, striking", align = "center"), 15 | h3("from a hidden base, have won", align = "center"), 16 | h2("their first victory against the", align = "center"), 17 | h1("evil Galactic Empire."), 18 | p("p creates a paragraph of text."), 19 | p("A new p() command starts a new paragraph. Supply a style attribute to change the format of the entire paragraph.", style = "font-family: 'times'; font-si16pt"), 20 | strong("strong() makes bold text."), 21 | em("em() creates italicized (i.e, emphasized) text."), 22 | br(), 23 | code("code displays your text similar to computer code"), 24 | div("div creates segments of text with a similar style. This division of text is all blue because I passed the argument 'style = color:blue' to div", style = "color:blue"), 25 | br(), 26 | p("span does the same thing as div, but it works with", 27 | span("groups of words", style = "color:blue"), 28 | "that appear inside a paragraph.") 29 | ) 30 | 31 | ) 32 | ) 33 | 34 | # Define server logic ---- 35 | server <- function(input, output) { 36 | 37 | } 38 | 39 | # Run the app ---- 40 | shinyApp(ui = ui, server = server) -------------------------------------------------------------------------------- /Course 7 - Web-Applications with Shiny in R/Example Apps/app2/www/rstudio.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SebKrantz/Data-Science-Programme/1f0ea0ea50a940f950b09e684e610aa684756ac6/Course 7 - Web-Applications with Shiny in R/Example Apps/app2/www/rstudio.png -------------------------------------------------------------------------------- /Course 7 - Web-Applications with Shiny in R/Example Apps/app3/app.R: -------------------------------------------------------------------------------- 1 | library(shiny) 2 | 3 | 4 | chlist <- as.list(unique(unclass(iris$Species))) 5 | names(chlist) <- levels(iris$Species) 6 | 7 | # Define UI ---- 8 | ui <- fluidPage( 9 | titlePanel("Basic widgets"), 10 | 11 | fluidRow( 12 | 13 | column(3, 14 | h3("Buttons"), 15 | actionButton("action", "Action"), 16 | br(), 17 | br(), 18 | submitButton("Submit")), 19 | 20 | column(3, 21 | h3("Single checkbox"), 22 | checkboxInput("checkbox", "Choice A", value = TRUE)), 23 | 24 | column(3, 25 | checkboxGroupInput("checkGroup", 26 | h3("Checkbox group"), 27 | choices = chlist, 28 | selected = 1)), 29 | 30 | column(3, 31 | dateInput("date", 32 | h3("Date input"), 33 | value = "2014-01-01")) 34 | ), 35 | 36 | fluidRow( 37 | 38 | column(3, 39 | dateRangeInput("dates", h3("Date range"))), 40 | 41 | column(3, 42 | fileInput("file", h3("File input"))), 43 | 44 | column(3, 45 | h3("Help text"), 46 | helpText("Note: help text isn't a true widget,", 47 | "but it provides an easy way to add text to", 48 | "accompany other widgets.")), 49 | 50 | column(3, 51 | numericInput("num", 52 | h3("Numeric input"), 53 | value = 1)) 54 | ), 55 | 56 | fluidRow( 57 | 58 | column(3, 59 | radioButtons("radio", h3("Radio buttons"), 60 | choices = list("Choice 1" = 1, "Choice 2" = 2, 61 | "Choice 3" = 3),selected = 1)), 62 | 63 | column(3, 64 | selectInput("select", h3("Select box"), 65 | choices = list("Choice 1" = 1, "Choice 2" = 2, 66 | "Choice 3" = 3), selected = 1)), 67 | 68 | column(3, 69 | sliderInput("slider1", h3("Sliders"), 70 | min = 0, max = 100, value = 50), 71 | sliderInput("slider2", "", 72 | min = 0, max = 100, value = c(25, 75)) 73 | ), 74 | 75 | column(3, 76 | textInput("text", h3("Text input"), 77 | value = "Enter text...")) 78 | ) 79 | 80 | ) 81 | 82 | # Define server logic ---- 83 | server <- function(input, output) { 84 | 85 | } 86 | 87 | # Run the app ---- 88 | shinyApp(ui = ui, server = server) -------------------------------------------------------------------------------- /Course 7 - Web-Applications with Shiny in R/Example Apps/census-app/app.R: -------------------------------------------------------------------------------- 1 | library(shiny) 2 | library(maps) 3 | library(mapproj) 4 | source("helpers.R") 5 | counties <- readRDS("data/counties.rds") 6 | 7 | 8 | ui <- fluidPage( 9 | titlePanel("censusVis"), 10 | 11 | sidebarLayout( 12 | sidebarPanel( 13 | helpText("Create demographic maps with 14 | information from the 2010 US Census."), 15 | 16 | selectInput("var", 17 | label = "Choose a variable to display", 18 | choices = c("Percent White", 19 | "Percent Black", 20 | "Percent Hispanic", 21 | "Percent Asian"), 22 | selected = "Percent White"), 23 | 24 | sliderInput("range", 25 | label = "Range of interest:", 26 | min = 0, max = 100, value = c(0, 100)) 27 | ), 28 | 29 | mainPanel( 30 | plotOutput("map") 31 | ) 32 | ) 33 | ) 34 | 35 | server <- function(input, output) { 36 | 37 | output$map <- renderPlot({ 38 | 39 | data <- counties[[tolower(substr(input$var, 9, 1000))]] 40 | 41 | colour <- switch(input$var, 42 | "Percent White" = "darkgreen", 43 | "Percent Black" = "black", 44 | "Percent Hispanic" = "darkorange", 45 | "Percent Asian" = "darkred") 46 | 47 | percent_map(var = data, 48 | color = colour, 49 | legend.title = sub("Percent", "%", input$var), 50 | max = input$range[2], 51 | min = input$range[1]) 52 | }) 53 | 54 | } 55 | 56 | shinyApp(ui, server) -------------------------------------------------------------------------------- /Course 7 - Web-Applications with Shiny in R/Example Apps/census-app/data/counties.rds: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SebKrantz/Data-Science-Programme/1f0ea0ea50a940f950b09e684e610aa684756ac6/Course 7 - Web-Applications with Shiny in R/Example Apps/census-app/data/counties.rds -------------------------------------------------------------------------------- /Course 7 - Web-Applications with Shiny in R/Example Apps/census-app/helpers.R: -------------------------------------------------------------------------------- 1 | # Note: percent map is designed to work with the counties data set 2 | # It may not work correctly with other data sets if their row order does 3 | # not exactly match the order in which the maps package plots counties 4 | percent_map <- function(var, color, legend.title, min = 0, max = 100) { 5 | 6 | # generate vector of fill colors for map 7 | shades <- colorRampPalette(c("white", color))(100) 8 | 9 | # constrain gradient to percents that occur between min and max 10 | var <- pmax(var, min) 11 | var <- pmin(var, max) 12 | percents <- as.integer(cut(var, 100, 13 | include.lowest = TRUE, ordered = TRUE)) 14 | fills <- shades[percents] 15 | 16 | # plot choropleth map 17 | map("county", fill = TRUE, col = fills, 18 | resolution = 0, lty = 0, projection = "polyconic", 19 | myborder = 0, mar = c(0,0,0,0)) 20 | 21 | # overlay state borders 22 | map("state", col = "white", fill = FALSE, add = TRUE, 23 | lty = 1, lwd = 1, projection = "polyconic", 24 | myborder = 0, mar = c(0,0,0,0)) 25 | 26 | # add a legend 27 | inc <- (max - min) / 4 28 | legend.text <- c(paste0(min, " % or less"), 29 | paste0(min + inc, " %"), 30 | paste0(min + 2 * inc, " %"), 31 | paste0(min + 3 * inc, " %"), 32 | paste0(max, " % or more")) 33 | 34 | legend("bottomleft", 35 | legend = legend.text, 36 | fill = shades[c(1, 25, 50, 75, 100)], 37 | title = legend.title) 38 | } -------------------------------------------------------------------------------- /Course 7 - Web-Applications with Shiny in R/Example Apps/google-trend-index/app.R: -------------------------------------------------------------------------------- 1 | library(shiny) 2 | library(shinythemes) 3 | 4 | # Load data 5 | trend_data <- read_csv("data/trend_data.csv") 6 | trend_description <- read_csv("data/trend_description.csv") 7 | 8 | # Define UI 9 | ui <- fluidPage(theme = shinytheme("lumen"), 10 | titlePanel("Google Trend Index"), 11 | sidebarLayout( 12 | sidebarPanel( 13 | 14 | # Select variable type of trend to plot 15 | selectInput(inputId = "type", 16 | label = strong("Trend index"), 17 | choices = c("Advertising & marketing" = "advert", 18 | "Education" = "educat", 19 | "Small business" = "smallbiz", 20 | "Travel" = "travel", 21 | "Unemployment" = "unempl"), 22 | selected = "travel"), 23 | 24 | # Descriptor text 25 | HTML("The index is set to 1.0 on January 1, 2004 and is 26 | calculated only for US search traffic."), 27 | 28 | # Line for visual separation 29 | hr(), 30 | 31 | # Select date range to be plotted 32 | dateRangeInput("date", strong("Date range"), 33 | start = "2007-01-01", end = "2017-07-31", 34 | min = "2007-01-01", max = "2017-07-31"), 35 | 36 | # Line for visual separation 37 | hr(), 38 | 39 | # Select whether to overlay smooth trend line 40 | checkboxInput(inputId = "smoother", 41 | label = strong("Overlay smooth trend line"), 42 | value = FALSE), 43 | 44 | # Display only if the smoother is checked 45 | conditionalPanel(condition = "input.smoother == true", 46 | sliderInput(inputId = "f", 47 | label = "Smoother span:", 48 | min = 0.01, max = 1, value = 0.67, step = 0.01, 49 | animate = animationOptions(interval = 100)), 50 | HTML("Higher values give more smoothness.") 51 | ) 52 | ), 53 | 54 | # Output: Description, lineplot, and reference 55 | mainPanel( 56 | textOutput(outputId = "description"), 57 | plotOutput(outputId = "lineplot"), 58 | tags$a(href="https://www.google.com/finance/domestic_trends", "Source: Google Domestic Trends")) 59 | ) 60 | ) 61 | 62 | # Define server function 63 | server <- function(input, output) { 64 | 65 | # Subset data 66 | selected_trends <- reactive({ 67 | req(input$date) 68 | validate(need(!is.na(input$date[1]) & !is.na(input$date[2]), "Error: Please provide both a start and an end date.")) 69 | validate(need(input$date[1] < input$date[2], "Error: Start date should be earlier than end date.")) 70 | subset(trend_data, 71 | type == input$type & 72 | date > input$date[1] & date < input$date[2] 73 | ) 74 | }) 75 | 76 | # Create scatterplot object the plotOutput function is expecting 77 | output$lineplot <- renderPlot({ 78 | color = "#434343" 79 | par(mar = c(4, 4, 1, 1)) 80 | plot(x = selected_trends()$date, y = selected_trends()$close, type = "l", 81 | xlab = "Date", ylab = "Trend index", 82 | col = color, fg = color, 83 | col.lab = color, col.axis = color) 84 | # Display only if smoother is checked 85 | if(input$smoother){ 86 | smooth_curve <- lowess(x = as.numeric(selected_trends()$date), y = selected_trends()$close, f = input$f) 87 | lines(smooth_curve, col = "#E6553A", lwd = 3) 88 | } 89 | }) 90 | 91 | # Pull in description of trend 92 | output$description <- renderText({ 93 | subset(trend_description, type == input$type)[["text"]] 94 | }) 95 | } 96 | 97 | # Create Shiny object 98 | shinyApp(ui = ui, server = server) 99 | -------------------------------------------------------------------------------- /Course 7 - Web-Applications with Shiny in R/Example Apps/google-trend-index/data/trend_description.csv: -------------------------------------------------------------------------------- 1 | type,text 2 | advert,"The Google Advertising & Marketing Index tracks queries related to marketing, advertising, ads, adsense, constant contact, public relations, etc." 3 | educat,"The Google Education Index tracks queries related to college, education, test, academy, barnes and noble, harvard, etc." 4 | smallbiz,"The Google Small Business Index tracks queries related to small business, make money, franchise, work from home, chamber or commerce, etc." 5 | travel,"The Google Travel Index tracks queries related to airlines, hotels, beach, southwest, las vegas, flights, etc." 6 | unempl,"The Google Unemployment Index tracks queries related to unemployment, food stamps, social security, edd, disability, etc." 7 | -------------------------------------------------------------------------------- /Course 7 - Web-Applications with Shiny in R/Example Apps/lesson2/app.R: -------------------------------------------------------------------------------- 1 | 2 | 3 | library(shiny) 4 | 5 | # Define UI ---- 6 | ui <- fluidPage( 7 | titlePanel("My Shiny App"), 8 | sidebarLayout( 9 | sidebarPanel( 10 | h2("Installation"), 11 | p("Shiny is available on CRAN, so you can install it in the usual way from your R console:"), 12 | code('install.packages("shiny")'), 13 | br(), br(), br(), br(), 14 | img(src = "rstudio.png", height = 70, width = 200), 15 | br(), 16 | "Shiny is a product of ", 17 | span("RStudio", style = "color:blue") 18 | ), 19 | mainPanel( 20 | h1("Introducing Shiny"), 21 | p("Shiny is a new package from RStudio that makes it ", 22 | em("incredibly easy "), 23 | "to build interactive web applications with R."), 24 | br(), 25 | p("For an introduction and live examples, visit the ", 26 | a("Shiny homepage.", 27 | href = "http://shiny.rstudio.com")), 28 | br(), 29 | h2("Features"), 30 | p("- Build useful web applications with only a few lines of code—no JavaScript required."), 31 | p("- Shiny applications are automatically 'live' in the same way that ", 32 | strong("spreadsheets"), 33 | " are live. Outputs change instantly as users modify inputs, without requiring a reload of the browser.") 34 | ) 35 | ) 36 | ) 37 | 38 | # Define server logic ---- 39 | server <- function(input, output) { 40 | 41 | } 42 | 43 | # Run the app ---- 44 | shinyApp(ui = ui, server = server) 45 | 46 | -------------------------------------------------------------------------------- /Course 7 - Web-Applications with Shiny in R/Example Apps/stockVis/app.R: -------------------------------------------------------------------------------- 1 | # Load packages ---- 2 | library(shiny) 3 | library(quantmod) 4 | 5 | # Source helpers ---- 6 | source("helpers.R") 7 | 8 | # User interface ---- 9 | ui <- fluidPage( 10 | titlePanel("stockVis"), 11 | 12 | sidebarLayout( 13 | sidebarPanel( 14 | helpText("Select a stock to examine. 15 | 16 | Information will be collected from Yahoo finance."), 17 | textInput("symb", "Symbol", "SPY"), 18 | 19 | dateRangeInput("dates", 20 | "Date range", 21 | start = "2013-01-01", 22 | min = "2013-01-01", # Because we load all data for a stock and subset after, we need to restrict the users choices by setting minimum and maximum date 23 | end = as.character(Sys.Date()), 24 | max = as.character(Sys.Date())), 25 | 26 | br(), 27 | br(), 28 | 29 | checkboxInput("log", "Plot y axis on log scale", 30 | value = FALSE), 31 | 32 | checkboxInput("adjust", 33 | "Adjust prices for inflation", value = FALSE) 34 | ), 35 | 36 | mainPanel(plotOutput("plot")) 37 | ) 38 | ) 39 | 40 | # Server logic 41 | server <- function(input, output) { 42 | 43 | # Efficient modularization: For each stock, we only load the data once 44 | dataInput <- reactive({ 45 | getSymbols(input$symb, src = "yahoo", 46 | from = "2013-01-01", 47 | to = as.character(Sys.Date()), 48 | auto.assign = FALSE) 49 | }) 50 | # If adjustment, we adjust the entire data for inflation 51 | adjInput <- reactive({ 52 | if (!input$adjust) return(dataInput()) 53 | adjust(dataInput()) 54 | }) 55 | # We can now subset the date range without the need to reload the data or readjust (see course 2 session on 'xts' time series for subsetting 'xts' using two dates) 56 | finalInput <- reactive({ 57 | adjInput()[paste(input$dates, collapse = "/")] 58 | }) 59 | # taking the log is relatively inexpensive, so we can do that on the fly in the plot function. 60 | output$plot <- renderPlot({ 61 | chartSeries(finalInput(), theme = chartTheme("white"), 62 | type = "line", log.scale = input$log, TA = NULL) 63 | }) 64 | 65 | } 66 | 67 | # Run the app 68 | shinyApp(ui, server) 69 | -------------------------------------------------------------------------------- /Course 7 - Web-Applications with Shiny in R/Example Apps/stockVis/helpers.R: -------------------------------------------------------------------------------- 1 | if (!exists(".inflation")) { 2 | .inflation <- getSymbols('CPIAUCNS', src = 'FRED', 3 | auto.assign = FALSE) 4 | } 5 | 6 | # adjusts Google finance data with the monthly consumer price index 7 | # values provided by the Federal Reserve of St. Louis 8 | # historical prices are returned in present values 9 | adjust <- function(data) { 10 | 11 | latestcpi <- last(.inflation)[[1]] 12 | inf.latest <- time(last(.inflation)) 13 | months <- split(data) 14 | 15 | adjust_month <- function(month) { 16 | date <- substr(min(time(month[1]), inf.latest), 1, 7) 17 | coredata(month) * latestcpi / .inflation[date][[1]] 18 | } 19 | 20 | adjs <- lapply(months, adjust_month) 21 | adj <- do.call("rbind", adjs) 22 | axts <- xts(adj, order.by = time(data)) 23 | axts[ , 5] <- Vo(data) 24 | axts 25 | } -------------------------------------------------------------------------------- /Course 7 - Web-Applications with Shiny in R/Example Apps/updateapp1/app.R: -------------------------------------------------------------------------------- 1 | server <- function(input, output, session) { 2 | 3 | observe({ 4 | txt <- paste("Value above is:", input$mytext) 5 | 6 | # here I'm essentially writing a result to the text box 7 | # called myresults 8 | updateTextInput(session, "myresults", value=txt) 9 | }) 10 | 11 | } 12 | 13 | ui <- basicPage( 14 | h3("An example of an update* function"), 15 | textInput("mytext", "Input goes here"), 16 | textInput("myresults", "Results will be printed here", "Initial value") 17 | ) 18 | 19 | shinyApp(ui = ui, server = server) -------------------------------------------------------------------------------- /Course 7 - Web-Applications with Shiny in R/Example Apps/updateapp2/app.R: -------------------------------------------------------------------------------- 1 | server <- function(input, output, session) { 2 | 3 | # Using observeEvent we're telling Shiny only to run this code 4 | # if mytext gets updated. 5 | observeEvent(input$mytext, { 6 | 7 | # myslider is a reactive but it does not trigger the code to 8 | # run here because we're using observeEvent and only specified 9 | # input$mytext 10 | input$myslider 11 | txt <- paste(input$mytext, sample(1:10000, 1)) 12 | updateTextInput(session, inputId = "myresults", value = txt) 13 | 14 | }) 15 | } 16 | 17 | ui <- basicPage( 18 | 19 | h3("The results text box only updates when you change the top text box (slider interactions do not trigger an update)."), 20 | sliderInput("myslider", "A slider:", min=0, max=1000, value=500), 21 | textInput("mytext", "Input goes here", value = "Initial value"), 22 | textInput("myresults", "Results will be printed here") 23 | 24 | ) 25 | 26 | shinyApp(ui = ui, server = server) -------------------------------------------------------------------------------- /Course 7 - Web-Applications with Shiny in R/Example Apps/updateapp3/app.R: -------------------------------------------------------------------------------- 1 | server <- function(input, output, session) { 2 | 3 | # first observer has lower priority so it runs second and will 4 | # overwrite the other observer 5 | observe({ 6 | txtA <- paste("First observer", input$mytext) 7 | updateTextInput(session, inputId = "myresults", value = txtA) 8 | }, priority = 1) 9 | 10 | # second observer has higher priority so it will run first and 11 | # then be overwritten 12 | observe({ 13 | txtB <- paste("Second observer", input$mytext) 14 | updateTextInput(session, inputId = "myresults", value = txtB) 15 | }, priority = 2) 16 | 17 | } 18 | 19 | ui <- basicPage( 20 | 21 | h3("Priority is higher for second observer so it runs first and then gets written over by the first observer"), 22 | textInput("mytext", "Input goes here"), 23 | textInput("myresults", "Results will be printed here", "") 24 | ) 25 | 26 | shinyApp(ui = ui, server = server) -------------------------------------------------------------------------------- /Course 7 - Web-Applications with Shiny in R/Example Apps/updatereactive-comparison/separated/app.R: -------------------------------------------------------------------------------- 1 | server <- function(input, output, session) { 2 | 3 | # Now if you change the slider only the slider result changes 4 | # and the text box result stays the same. This is because 5 | # we isolated the reactive values in their own reactive function 6 | 7 | txt <- reactive({paste(input$mytext, sample(1:100, 1))}) 8 | val <- reactive({paste(input$myslider, sample(1:100, 1), sep="-")}) 9 | 10 | 11 | observe({ 12 | res <- paste0(txt(), " | Slider ", val()) 13 | updateTextInput(session, "myresults", value = res) 14 | }) 15 | 16 | 17 | } 18 | 19 | ui <- basicPage( 20 | 21 | h3("Changes to the text box and slider are separated so that a change to the text box will not affect the slider part of the results textbox"), 22 | sliderInput("myslider", "A slider:", min=0, max=1000, value=500), 23 | textInput("mytext", "Input goes here", "Text"), 24 | textInput("myresults", "Results will be printed here", "Initial value") 25 | 26 | ) 27 | 28 | shinyApp(ui = ui, server = server) -------------------------------------------------------------------------------- /Course 7 - Web-Applications with Shiny in R/Example Apps/updatereactive-comparison/together/app.R: -------------------------------------------------------------------------------- 1 | #### server 2 | server <- function(input, output, session) { 3 | 4 | # Notice that even if you only change the text box that the 5 | # slider code also runs and gets changed. The reverse is also 6 | # true. You might want to isolate these pieces. 7 | observe({ 8 | txt <- paste(input$mytext, sample(1:100, 1)) 9 | val <- paste(input$myslider, sample(1:100, 1), sep="-") 10 | 11 | res <- paste0(txt, " | Slider ", val) 12 | updateTextInput(session, "myresults", value = res) 13 | }) 14 | } 15 | 16 | 17 | ui <- basicPage( 18 | 19 | h3("Change to text OR slider changes both parts of results text box"), 20 | sliderInput("myslider", "A slider:", min=0, max=1000, value=500), 21 | textInput("mytext", "Input goes here", "Text"), 22 | textInput("myresults", "Results will be printed here", "Initial value") 23 | 24 | ) 25 | 26 | shinyApp(ui = ui, server = server) -------------------------------------------------------------------------------- /Course 7 - Web-Applications with Shiny in R/Example Apps/updatereactiveapp1/app.R: -------------------------------------------------------------------------------- 1 | server <- function(input, output, session) { 2 | 3 | # this is my reactive function -- I'm using it to 4 | # isolate reactions related to the text box 5 | mystring <- reactive({ 6 | paste(input$mytext, " is what the user types") 7 | }) 8 | 9 | observe({ 10 | # The reactive will run each time the textbox changes and 11 | # print results to the console. 12 | txt <- mystring() 13 | updateTextInput(session, inputId = "myresults", value = txt) 14 | }) 15 | 16 | } 17 | 18 | ui <- basicPage( 19 | 20 | h3("The reactive generates a string output which is added to the results text box"), 21 | textInput("mytext", "Input goes here"), 22 | textInput("myresults", "Results will be printed here", "") 23 | 24 | ) 25 | 26 | shinyApp(ui = ui, server = server) -------------------------------------------------------------------------------- /Course 7 - Web-Applications with Shiny in R/Example Apps/updatereactiveapp2/app.R: -------------------------------------------------------------------------------- 1 | server <- function(input, output, session) { 2 | 3 | # since both mytext and myslider are in the reactive 4 | # they both trigger the code to run 5 | myresults <- reactive({ 6 | paste(input$mytext, input$myslider) # Use isolate(input$myslider) to achieve the same as the reactiveEvent function below 7 | }) 8 | 9 | # eventReactive here tells Shiny only to trigger this code 10 | # when mytext changes 11 | myresults_lim <- eventReactive(input$mytext, { 12 | paste(input$mytext, input$myslider) 13 | }) 14 | 15 | observe(updateTextInput(session, "myresults", value = myresults())) 16 | observe(updateTextInput(session, "myresults_lim", value = myresults_lim())) 17 | 18 | 19 | } 20 | 21 | ui <- basicPage( 22 | 23 | h3("Using eventReactive to limit reactions."), 24 | sliderInput("myslider", "", min=0, max=1000, value=500), 25 | textInput("mytext", "Input goes here"), 26 | textInput("myresults", "Text box + slider (updates when either changes)", "Initial value"), 27 | textInput("myresults_lim", "Text box + slider (updates when text box changes)", "Initial value") 28 | 29 | ) 30 | 31 | shinyApp(ui = ui, server = server) -------------------------------------------------------------------------------- /Course 7 - Web-Applications with Shiny in R/Example Apps/updatereactiveoutput/app.R: -------------------------------------------------------------------------------- 1 | server <- function(input, output, session) { 2 | 3 | # when select box changes, we get a different dataset 4 | dat <- reactive(get(input$dataset)) 5 | 6 | # Based on the dataset, this updates so we can see the variables of the dataset 7 | observeEvent(input$dataset, { 8 | 9 | updateSelectizeInput(session, "vars", choices = names(dat())) 10 | 11 | }) 12 | 13 | # This re-executes if either dat() or input$vars changes 14 | output$summ <- renderPrint({ 15 | 16 | # input$vars is NULL if no variables selected, otherwise a character string 17 | vars <- input$vars 18 | data <- dat() 19 | 20 | # This is meant to prevent errors from empty vars or when switching datasets 21 | if(length(vars) && all(vars %in% names(data))) 22 | print(summary(data[vars])) 23 | 24 | }) 25 | 26 | } 27 | 28 | ui <- fluidPage( 29 | 30 | titlePanel("An app using an observe, reactive and render"), 31 | 32 | sidebarLayout( 33 | sidebarPanel( 34 | selectInput("dataset", "Select Dataset", choices = c("iris", "mtcars", "airquality"), selected = "iris"), 35 | selectizeInput("vars", "Select Variables", choices = names(iris), 36 | options = list(placeholder = "Choose variables"), multiple = TRUE) 37 | ), # end sidebar panel 38 | 39 | mainPanel( 40 | tabsetPanel( 41 | tabPanel("Summary", verbatimTextOutput("summ")) 42 | ) 43 | ) # end main panel 44 | ) 45 | ) 46 | 47 | shinyApp(ui = ui, server = server) -------------------------------------------------------------------------------- /Course 7 - Web-Applications with Shiny in R/Full Apps/census-mapper/app.R: -------------------------------------------------------------------------------- 1 | ############################## 2 | # Uganda 2014 Census Map 3 | ############################## 4 | 5 | suppressPackageStartupMessages({ 6 | library(shiny) 7 | library(shinyBS) 8 | library(collapse) 9 | library(leaflet) 10 | library(sf) 11 | library(scales) 12 | library(htmltools) 13 | library(RColorBrewer) 14 | }) 15 | 16 | # rm(list = ls()) 17 | load("app_DATA.RData") 18 | 19 | idvars <- c("Region", "District", "County", "Subcounty", "Parish") 20 | 21 | names(cens_vars_list)[1L] <- "Composite Indices" 22 | 23 | agglabs <- setNames(idvars, paste0(idvars, " (", 24 | c(fnrow(DATA_Region), fnrow(DATA_District), fnrow(DATA_County), 25 | fnrow(DATA_Subcounty), fnrow(DATA)), ")")) 26 | 27 | genpopup <- function(data, colvar = "POP_M", oth = c("POP", "HDI"), 28 | idvars = c("Region", "District", "County", "Subcounty", "Parish")) { 29 | ids <- idvars[idvars %in% names(data)] 30 | if(colvar %!in% oth) oth <- c(oth, colvar) 31 | vars <- c(ids, oth) 32 | lhs <- paste0("
", vars, ":") 33 | lhs[1L] <- substr(lhs[1L], 6L, 10000L) 34 | pop <- c(as.vector(lhs, "list"), .subset(data, vars)) 35 | if(!all(int <- vapply(pop[oth], is.integer, TRUE))) 36 | pop[oth][!int] <- lapply(pop[oth][!int], round, 3L) 37 | o <- seq(1L, 2L*length(vars), 2L) 38 | o <- order(c(o, o + 1L)) 39 | do.call(paste, pop[o]) 40 | } 41 | 42 | 43 | ui <- source(file.path("geoUI.R"), local = TRUE)$value 44 | 45 | server <- function(input, output, session) { 46 | source(file.path("geoSERVER.R"), local = TRUE)$value 47 | } 48 | 49 | shinyApp(ui = ui, server = server) 50 | 51 | -------------------------------------------------------------------------------- /Course 7 - Web-Applications with Shiny in R/Full Apps/census-mapper/app_DATA.RData: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SebKrantz/Data-Science-Programme/1f0ea0ea50a940f950b09e684e610aa684756ac6/Course 7 - Web-Applications with Shiny in R/Full Apps/census-mapper/app_DATA.RData -------------------------------------------------------------------------------- /Course 7 - Web-Applications with Shiny in R/Full Apps/census-mapper/census-mapper.Rproj: -------------------------------------------------------------------------------- 1 | Version: 1.0 2 | 3 | RestoreWorkspace: Default 4 | SaveWorkspace: Default 5 | AlwaysSaveHistory: Default 6 | 7 | EnableCodeIndexing: Yes 8 | UseSpacesForTab: Yes 9 | NumSpacesForTab: 2 10 | Encoding: UTF-8 11 | 12 | RnwWeave: knitr 13 | LaTeX: pdfLaTeX 14 | -------------------------------------------------------------------------------- /Course 7 - Web-Applications with Shiny in R/Full Apps/census-mapper/geoSERVER.R: -------------------------------------------------------------------------------- 1 | 2 | ## Interactive Map 3 | 4 | mapdata <- reactive({ 5 | switch(input$agglev, 6 | Region = DATA_Region, 7 | District = DATA_District, 8 | County = DATA_County, 9 | Subcounty = DATA_Subcounty, 10 | Parish = DATA, 11 | stop("Unknown level of aggregation")) 12 | }) 13 | 14 | 15 | observe({ 16 | 17 | if(nzchar(input$topic)) { 18 | ch <- cens_vars_list[[input$topic]] 19 | updateSelectInput(session, "color", choices = ch, 20 | selected = if(input$topic == "Population Composition") "POP" else NULL) 21 | } 22 | 23 | }) 24 | 25 | observe({ 26 | 27 | if(nzchar(input$topic) && nzchar(input$color)) { 28 | ch <- cens_vars_list[[input$topic]] 29 | hp <- attr(ch, "HasPerc") 30 | if(isTRUE(hp[match(input$color, unattrib(ch))])) { 31 | updateRadioButtons(session, "unit", 32 | choices = c("Number", "Percent", "Number per Km2"), 33 | inline = TRUE, selected = "Percent") 34 | } else { 35 | updateRadioButtons(session, "unit", 36 | choices = c("Number", "Number per Km2"), 37 | inline = TRUE, selected = "Number") 38 | 39 | } 40 | } 41 | 42 | }) 43 | 44 | # Create the map 45 | 46 | output$map <- renderLeaflet({ 47 | 48 | leaflet() %>% # DATA 49 | addProviderTiles('CartoDB.Positron', group = "CartoDB Positron") %>% 50 | addProviderTiles('CartoDB.DarkMatter', group = "CartoDB DarkMatter") %>% 51 | addTiles(group="Open Street Map", attribution = '© Sebastian Krantz 2021 | Open Street Map') %>% 52 | addProviderTiles('OpenTopoMap', group = "Open Topo Map") %>% 53 | addTiles(urlTemplate = 'https://mts1.google.com/vt/lyrs=m&x={x}&y={y}&z={z}', group="Google Maps", attribution = '© Sebastian Krantz 2021 | Maps by Google') %>% 54 | addTiles(urlTemplate = 'https://mts1.google.com/vt/lyrs=p&x={x}&y={y}&z={z}', group="Google Terrain", attribution = '© Sebastian Krantz 2021 | Maps by Google') %>% 55 | addTiles(urlTemplate = 'https://mts1.google.com/vt/lyrs=s,h&x={x}&y={y}&z={z}', group="Google Hybrid", attribution = '© Sebastian Krantz 2021 | Maps by Google') %>% 56 | addTiles(urlTemplate = 'https://mts1.google.com/vt/lyrs=s&hl=en&src=app&x={x}&y={y}&z={z}', group="Google Satellite", attribution = '© Sebastian Krantz 2021 | Maps by Google') %>% 57 | addProviderTiles('Esri.WorldStreetMap', group = "Esri World Street Map") %>% 58 | addProviderTiles('Esri.WorldTopoMap', group = "Esri World Topo Map") %>% 59 | addProviderTiles('Esri.WorldImagery', group = "Esri World Imagery") %>% 60 | addProviderTiles('Esri.OceanBasemap', group = "Esri Ocean and Rivers") %>% 61 | addProviderTiles('NASAGIBS.ViirsEarthAtNight2012', group = "NASA Nightlights 2012") %>% 62 | setView(lng = 32.5, lat = 1.4, zoom = 8) %>% # lng = 0, lat = 20, zoom = 3 63 | addScaleBar(position = "bottomright", options = scaleBarOptions(maxWidth = 150)) %>% 64 | addMeasure( 65 | position = "bottomright", 66 | primaryLengthUnit = "meters", 67 | primaryAreaUnit = "sqmeters", 68 | activeColor = "#3D535D", 69 | completedColor = "#7D4479") %>% 70 | addEasyButton(easyButton( 71 | icon="fa-globe", title="Zoom to Level 3", 72 | onClick=JS("function(btn, map){ map.setZoom(3); }"))) %>% 73 | addEasyButton(easyButton( 74 | icon="fa-crosshairs", title="Locate Me", 75 | onClick=JS("function(btn, map){ map.locate({setView: true}); }"))) %>% 76 | addLayersControl(baseGroups = c("CartoDB Positron", "CartoDB DarkMatter", 77 | "Open Street Map", "Open Topo Map", 78 | "Google Maps", "Google Terrain", 79 | "Google Hybrid", "Google Satellite", 80 | "Esri World Street Map", 81 | "Esri World Topo Map", 82 | "Esri World Imagery", 83 | "Esri Ocean and Rivers", 84 | "NASA Nightlights 2012"), 85 | overlayGroups = "Choropleth Layer") 86 | 87 | }) 88 | 89 | 90 | # adding slider delay https://stackoverflow.com/questions/32235525/delay-on-sliderinput 91 | input_opacity <- debounce(reactive(input$opacity), 600) 92 | 93 | INPUTS <- reactive({ 94 | if(nzchar(input$topic) && nzchar(input$color)) { 95 | data <- mapdata() 96 | colvar <- if(input$unit == "Percent") paste0(input$color, "_P") else input$color 97 | colorData <- .subset2(data, colvar) 98 | if(input$unit == "Number per Km2") colorData <- colorData / .subset2(data, "AREA") 99 | 100 | CFUN <- identity 101 | if (length(colorData) && fndistinct(colorData) < 8L) { 102 | pal <- colorFactor(input$palette, qF(colorData)) 103 | } else { 104 | if(input$discbreaks) { 105 | if (input$logcolor) { 106 | pal <- colorBin(input$palette, colorData, 107 | bins = log_breaks(n = 7, base = 10)(colorData), pretty = FALSE) 108 | } else { 109 | pal <- colorBin(input$palette, colorData, bins = 7, pretty = TRUE) 110 | } 111 | } else { 112 | if (input$logcolor) { 113 | colorData <- replace_Inf(log10(colorData)) 114 | pal <- colorNumeric(input$palette, colorData) 115 | CFUN <- function(x) 10^x 116 | } else { 117 | pal <- colorNumeric(input$palette, colorData) 118 | } 119 | } 120 | } 121 | list(topic = input$topic, color = input$color, unit = input$unit, popup = genpopup(data, colvar), 122 | colvar = colvar, colorData = colorData, pal = pal, CFUN = CFUN, data = data, agglev = input$agglev) 123 | } else NULL 124 | 125 | }) %>% debounce(500) # 300 126 | 127 | observe({ 128 | 129 | IN <- INPUTS() 130 | 131 | if(!is.null(IN)) { 132 | 133 | leafletProxy("map", data = IN$data) %>% 134 | clearShapes() %>% clearControls() %>% 135 | addPolygons( 136 | popup = IN$popup, 137 | stroke = input$stroke, 138 | weight = 0.5, 139 | opacity = input_opacity(), 140 | color = "grey", # pal(colorData), # NA, # "black" 141 | fillColor = IN$pal(IN$colorData), # log(POP) 142 | fillOpacity = input_opacity(), 143 | smoothFactor = 0.2, # 0.1 144 | noClip = TRUE, 145 | highlightOptions = list( 146 | stroke = input$stroke, 147 | weight = 1, 148 | opacity = 1, 149 | color = "white", 150 | # dashArray = "", 151 | fillOpacity = 1, 152 | bringToFront = TRUE 153 | ), 154 | label = paste0("", .subset2(IN$data, IN$agglev), ": ", round(IN$CFUN(IN$colorData), 2)) %>% lapply(HTML), 155 | labelOptions = labelOptions( 156 | style = list("font-weight" = "normal", padding = "3px 8px"), 157 | textsize = "15px", 158 | direction = "auto"), 159 | group = "Choropleth Layer" 160 | ) %>% 161 | leaflet::addLegend(pal = IN$pal, values = IN$colorData, opacity = 0.9, # input_opacity(), 162 | labFormat = labelFormat(transform = IN$CFUN), 163 | title = if(IN$topic == "Composite Indices") "Index [0 - 1]" else 164 | switch(IN$unit, Number = "Population", Percent = "Percent", "Number per Km2" = "Pop. per Km2", stop("Unknown unit")), 165 | position = "bottomleft") # , group = "Choropleth Layer" 166 | 167 | } 168 | 169 | }) 170 | 171 | 172 | -------------------------------------------------------------------------------- /Course 7 - Web-Applications with Shiny in R/Full Apps/census-mapper/geoUI.R: -------------------------------------------------------------------------------- 1 | shinyUI(fluidPage(div(class="outer", 2 | 3 | tags$head( 4 | # Include our custom CSS 5 | includeCSS("styles.css") 6 | ), 7 | 8 | # If not using custom CSS, set height of leafletOutput to a number instead of percent 9 | leafletOutput("map", width="100%", height="100%"), 10 | 11 | # Shiny versions prior to 0.11 should use class = "modal" instead. 12 | absolutePanel(id = "controls", class = "panel panel-default", fixed = TRUE, 13 | draggable = FALSE, top = 130, left = "auto", right = 20, bottom = "auto", 14 | width = 335, height = "auto", cursor = "auto", 15 | 16 | h2("Uganda 2014 Census", style = "color: #262626; padding-top: 0;"), 17 | 18 | tabsetPanel(id="geotab", 19 | tabPanel("Data", 20 | div(id='myDiv', 21 | selectInput("topic", "Topic", choices = names(cens_vars_list)), # c("Select a Topic" = "", names(cens_vars_list)) # , selected = "Composite Indices" 22 | selectInput("color", "Indicator", choices = c("Select an Indicator" = "")), # c("Human Development Index" = "HDI") # cens_vars_list[["Composite Indices"]], selected = "HDI"), 23 | conditionalPanel("input.topic != 'Composite Indices' && input.topic != ''", 24 | radioButtons("unit", "Unit", choices = "Number", inline = TRUE) 25 | ), 26 | tags$hr(), 27 | selectInput("agglev", "Level of Aggregation", choices = agglabs, selected = "District") 28 | 29 | ) 30 | ), 31 | tabPanel("Appearance", 32 | div(id='myDiv', 33 | selectInput("palette", "Color Palette", choices = list(`Viridis Palettes` = c("viridis","magma","inferno","plasma"), 34 | `R Color Brewer - Sequential` = rev(row.names.data.frame(brewer.pal.info)[brewer.pal.info$category == "seq"]), 35 | `R Color Brewer - Divergent` = rev(row.names.data.frame(brewer.pal.info)[brewer.pal.info$category == "div"])), 36 | selected = "viridis") 37 | ), 38 | numericInput("opacity", "Opacity", min = 0, max = 1, value = 0.7, step = 0.1), 39 | tags$hr(), 40 | checkboxInput("logcolor", "Log10 Scale"), 41 | checkboxInput("discbreaks", "Discrete Breaks"), 42 | checkboxInput("stroke", "Stroke Polygon Shapes", TRUE) 43 | 44 | ) 45 | ) 46 | 47 | )))) 48 | -------------------------------------------------------------------------------- /Course 7 - Web-Applications with Shiny in R/Full Apps/census-mapper/styles.css: -------------------------------------------------------------------------------- 1 | input[type="number"] { 2 | max-width: 80%; 3 | } 4 | 5 | div.outer { 6 | position: fixed; 7 | top: 0; /* 45px; */ 8 | left: 0; 9 | right: 0; 10 | bottom: 0; 11 | overflow: hidden; 12 | padding: 0; 13 | } 14 | 15 | /* Customize fonts */ 16 | body, label, input, button, select { 17 | font-family: 'Helvetica Neue', Helvetica; 18 | font-weight: 200; 19 | } 20 | .control-label { 21 | font-weight: bold; 22 | } 23 | 24 | h1, h2, h3, h4 { 25 | font-weight: 400; 26 | } 27 | 28 | .tabbable > .nav > li > a { 29 | background-color: transparent; 30 | color: #333; 31 | font-weight: bold; 32 | } 33 | .tabbable > .nav > li > a:hover { 34 | color: #0067e6; 35 | } 36 | .tabbable > .nav > li[class=active] > a { 37 | background-color: #e6e6e6; 38 | color: #0067e6; 39 | } 40 | 41 | .checkbox, .radio-inline { 42 | color: black; 43 | } 44 | 45 | #myDiv { 46 | padding: 15px 0 0 0; 47 | } 48 | #myDiv2 { 49 | padding: 15px 0 0 0; 50 | } 51 | #myDiv3 { 52 | padding: 0 0 0 0; 53 | } 54 | #myDiv4 { 55 | padding: 15px 0 0 0; /* cursor: pointer; */ 56 | } 57 | 58 | #controls { 59 | /* Appearance */ 60 | border-radius: 20px; /* Rounded Corners */ 61 | border: 0; 62 | background-color: lightslategray ; /*white*/ 63 | padding: 0 20px 20px 20px; /*0 20px 20px 20px;*/ 64 | /* cursor: move; */ 65 | /* Fade out while not hovering */ 66 | opacity: 0.65; 67 | zoom: 0.9; 68 | transition: opacity 0 500ms; /*1s*/ 69 | } 70 | #controls:hover { 71 | /* Fade in while hovering */ 72 | opacity: 0.95; 73 | transition-delay: 0; 74 | } 75 | 76 | /* If not using map tiles, show a white background */ 77 | .leaflet-container { 78 | background-color: white !important; 79 | } 80 | -------------------------------------------------------------------------------- /Course 7 - Web-Applications with Shiny in R/Full Apps/shiny-data-portal/app.R: -------------------------------------------------------------------------------- 1 | ############################## 2 | # Data Portal Application 3 | ############################## 4 | 5 | # Required R Packages 6 | suppressPackageStartupMessages({ 7 | library(shiny) # Shiny: The Web application framework we are working with 8 | library(shinyBS) # Shiny Bootstrap: Bootstrap web themes and features for shiny 9 | library(DT) # A wrapper for JavaScript library 'DataTables' 10 | library(haven) # Read and write STATA, SPSS and SAS files 11 | library(readr) # Read and write CSV and TSV/TAB files 12 | library(writexl) # Write excel 13 | library(ggcorrplot) # Fancy plot of correlation matrix 14 | library(qtlcharts) # Fancy interactive plot of correlation matrix + scatter chart 15 | library(collapse) # Fast Data Manipulation and Transformation 16 | }) 17 | 18 | # Some global options affecting appearance 19 | options(digits = 3L, 20 | width = 100L, 21 | htmlwidgets.TOJSON_ARGS = list(na = 'string', digits = 6L), # better option ? 22 | shiny.sanitize.errors = FALSE) # This makes sure shiny displays any error messages 23 | 24 | # Load Data 25 | load("load_all.RData") 26 | 27 | # Small functions to help process data on the server side 28 | source("helpers.R") 29 | 30 | # This creates the website, integrating the code in ui.R, which creates the 'Data Access' tab. 31 | 32 | # Set title and provide logo for application 33 | title <- "My Data Portal" 34 | logo <- "logo.png" # should be placed in www folder in the project directory, and be png format. 35 | 36 | ui <- bootstrapPage('', # Can run print(ui) to see the HTML code for the website after running this. 37 | 38 | # This includes a CSS stylesheet 'style.css' setting the appearance of the app. This sheet can be edited separately. 39 | includeCSS("style.css"), 40 | 41 | # This compounds the title with the logo on the left 42 | navbarPage(div(img(src = logo, height = 40, style = "position: absolute; top: 0; bottom:0; left: 0; right:0; 43 | margin-top: auto; margin-bottom: auto; margin-left: 5px; margin-right: 50px;"), 44 | title, style = "margin-left: 45px;"), 45 | 46 | # This is for the browser tab 47 | windowTitle = tags$head(tags$link(rel = "icon", type = "image/png", href = logo), 48 | tags$title(title)), 49 | 50 | # Select default tab when calling site 51 | selected = "Data Access", 52 | 53 | # Read code from ui.R 54 | tabPanel("Data Access", 55 | source(file.path("ui_code.R"), local = TRUE)$value 56 | ), 57 | 58 | # 'Data Catalog' tab 59 | tabPanel("Data Catalog", 60 | div(class = "outer", 61 | p(" "), 62 | tabsetPanel( 63 | tabPanel("Data Sources", 64 | p(" "), 65 | DT::dataTableOutput("datasources")), 66 | tabPanel("Datasets", 67 | p(" "), 68 | DT::dataTableOutput("datasetdesc")), 69 | tabPanel("Variables", 70 | p(" "), 71 | div(class = "indicatortable", 72 | DT::dataTableOutput("dataoverview") 73 | )) 74 | ) 75 | ) 76 | ), 77 | 78 | # About tab (can include more sections and useful links), see ?shiny::tags 79 | tabPanel("About", 80 | div(class = "AboutContent", 81 | h3("Purpose of the Portal"), 82 | p('A free Shiny Application to host, filter, aggregate and and download data in various formats. 83 | It can be set up by anyone for any purpose and with any data using the source code and instructions (README.md) available on Github:'), 84 | a("Source Code", href = "https://github.com/SebKrantz/shiny-data-portal", target = "_blank"), 85 | h3("Details"), 86 | p("The app was built using the 'shiny' web-application framework in R (and some small custom HTML and CSS). 87 | It is currently serviced with macroeconomic data for Uganda downloaded and with various sources using various R API packages (IMFData, wbstats, Rilostat, tradestatistics) as well as data from the Bank of Uganda. 88 | The app was built by Sebastian Krantz (ODI Fellow in the Ugandan Ministry of Finance, Planning and Economic Development 2020/21).") 89 | # Source code is available on github and released under a GPL 2.0 license (so it may be appropriated and adapted by other organizations under certain conditions). "), 90 | ), 91 | tags$footer( 92 | HTML("Copyright © 2021, Sebastian Krantz") 93 | ) 94 | ) 95 | ) 96 | ) 97 | 98 | 99 | # This reads the server side code in server.R and creates the server function. 100 | server <- function(input, output, session) { 101 | 102 | source(file.path("server_code.R"), local = TRUE)$value 103 | 104 | } 105 | 106 | # This puts everything together and runs the application. 107 | shinyApp(ui = ui, server = server) -------------------------------------------------------------------------------- /Course 7 - Web-Applications with Shiny in R/Full Apps/shiny-data-portal/helpers.R: -------------------------------------------------------------------------------- 1 | # Small functions to help process data on the server side 2 | selectvars <- function(x, v, exc = FALSE) { 3 | if(exc) v <- -ckmatch(v, names(x)) 4 | get_vars(x, v) 5 | } 6 | 7 | vlabdf <- function(X) { 8 | res <- lapply(unattrib(X), attr, "label") 9 | res[vapply(res, is.null, TRUE)] <- "-" 10 | unlist(res, use.names = FALSE) 11 | } 12 | 13 | vlabclsrc <- function(X) { 14 | ntd <- function(x) if(length(x)) x else "-" 15 | ff <- function(x) c(paste0(paste(class(x), collapse = " "), " (", typeof(x),")"), ntd(attr(x, "label")), ntd(attr(x, "source"))) 16 | qDF(setColnames(t(vapply(X, ff, character(3))), 17 | c("Class (Storage Mode)", "Label", "Source")), "Variable") 18 | } 19 | 20 | namlabHTML <- function(df) { 21 | if(is.list(df) && length(df) > 1L) names(df) <- paste0("", names(df), "
", vlabdf(df), "") 22 | df 23 | } 24 | 25 | mysummary <- function(df, labels = TRUE) { 26 | ord <- as.integer(c(3,1,4,2,5,6,7,8,9)) 27 | sumf <- function(x) if(is.numeric(x)) c(fndistinct.default(x), fmedian.default(x), qsu.default(x, higher = TRUE))[ord] else 28 | c(fnobs.default(x), fndistinct.default(x), rep(NA_real_, 7L)) 29 | res <- t(vapply(df, sumf, numeric(9))) 30 | colnames(res) <- c("N","Distinct","Mean","Median","SD","Min","Max","Skewness","Kurtosis") 31 | res <- qDF(print.qsu(res, return = TRUE), "Variable") 32 | if(labels) res$Label <- vlabels(df) 33 | return(res) 34 | } 35 | 36 | renameSTATA <- function(x) { 37 | names(x) <- gsub("\\.", "_", names(x)) 38 | x 39 | } 40 | 41 | transpose_for_excel <- function(data) { 42 | data_transposed <- data.table::transpose(num_vars(data)) 43 | names(data_transposed) <- as.character(data[[1]]) 44 | add_vars(data_transposed, "front") <- list(Variable = names(num_vars(data)), 45 | Label = vlabels(num_vars(data))) 46 | data_transposed 47 | } 48 | -------------------------------------------------------------------------------- /Course 7 - Web-Applications with Shiny in R/Full Apps/shiny-data-portal/load_all.RData: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SebKrantz/Data-Science-Programme/1f0ea0ea50a940f950b09e684e610aa684756ac6/Course 7 - Web-Applications with Shiny in R/Full Apps/shiny-data-portal/load_all.RData -------------------------------------------------------------------------------- /Course 7 - Web-Applications with Shiny in R/Full Apps/shiny-data-portal/shiny-data-portal.Rproj: -------------------------------------------------------------------------------- 1 | Version: 1.0 2 | 3 | RestoreWorkspace: Default 4 | SaveWorkspace: Default 5 | AlwaysSaveHistory: Default 6 | 7 | EnableCodeIndexing: Yes 8 | UseSpacesForTab: Yes 9 | NumSpacesForTab: 2 10 | Encoding: UTF-8 11 | 12 | RnwWeave: knitr 13 | LaTeX: pdfLaTeX 14 | -------------------------------------------------------------------------------- /Course 7 - Web-Applications with Shiny in R/Full Apps/shiny-data-portal/style.css: -------------------------------------------------------------------------------- 1 | /* 2 | CSS Stylesheet for the App 3 | Learn CSS at: https://www.w3schools.com/css/ 4 | */ 5 | 6 | /* This is the Navigation bar itself */ 7 | .navbar-default { 8 | background-color: #262626; 9 | margin-top: 0; 10 | margin-bottom: 0; 11 | border: 0; 12 | font-size: 13px; 13 | } 14 | 15 | /* This regulates colour of navigation bar items and hovering effect over */ 16 | .navbar-default .navbar-nav > li > a { 17 | color: #999999 18 | } 19 | .navbar-default .navbar-nav > li > a:hover { 20 | color: #ffffff 21 | } 22 | 23 | /* This is the tab panel on the top bar, when selected or clicked on */ 24 | .navbar-default .navbar-nav > .active > a, 25 | .navbar-default .navbar-nav > .active > a:hover, 26 | .navbar-default .navbar-nav > .active > a:focus { 27 | color: #ffffff; 28 | background: #666666; 29 | } 30 | 31 | /* This is the Title of the Website */ 32 | .navbar-default .navbar-brand, 33 | .navbar-default .navbar-brand:hover, 34 | .navbar-default .navbar-brand:focus { 35 | color: #f2f2f2 36 | } 37 | 38 | /* Tabs in Main or side panel */ 39 | .tabbable > .nav > li > a { 40 | background-color: transparent; 41 | color:#0067e6; 42 | border: 0 43 | } 44 | .tabbable > .nav > li[class=active] > a { 45 | background-color: #0067e6; 46 | color:white; 47 | border: 0 48 | } 49 | 50 | /* Main Panels */ 51 | #side { 52 | background-color: #404040; 53 | color: #d9d9d9; 54 | zoom: 1; 55 | padding: 1%; 56 | right: auto; 57 | width: 20%; 58 | min-height: 100%; 59 | height: auto; 60 | /* position: absolute; Already inserted by absolutepanel. */ 61 | overflow-y: auto; 62 | } 63 | 64 | #main { 65 | padding: 1%; 66 | left: 20%; 67 | width: 80%; 68 | height: 100%; 69 | } 70 | 71 | /* Tables */ 72 | table, td { 73 | margin-top: 10px; 74 | caption-side: bottom; 75 | } 76 | 77 | .summarytable { 78 | margin-top: 10px; 79 | caption-side: bottom; 80 | white-space: nowrap; 81 | height: 90vh; 82 | overflow-y: auto /* scroll */ 83 | } 84 | 85 | .indicatortable { 86 | margin-top: 10px; 87 | caption-side: bottom; 88 | white-space: nowrap; 89 | height: 90vh; 90 | overflow-x: hidden; /* scrolling already enabled on server ... */ 91 | overflow-y: auto /*scroll */ 92 | } 93 | 94 | #DATAtable th { 95 | font-weight: normal; 96 | } 97 | 98 | /* headers */ 99 | h1, h2, h3, h4, h5, h6 { 100 | color: #FF6600; 101 | padding-top: 10px; /* 10px */ 102 | } 103 | 104 | /* Text output */ 105 | .shiny-text-output { 106 | width: 100%; 107 | height: 90vh; 108 | overflow-x: auto; 109 | overflow-y: auto; 110 | } 111 | 112 | /* plot output: https://stackoverflow.com/questions/26782041/scaling-shiny-plots-to-window-height */ 113 | .shiny-plot-output { 114 | height: 90vh !important; 115 | } 116 | 117 | /* Correct line-wrapping or radio buttons: https://stackoverflow.com/questions/25730961/bootstrap-radio-inline-line-wrapping-and-stacked-radio-buttons/25732098 */ 118 | .radio-inline+.radio-inline { 119 | margin-left: 0; 120 | } 121 | .radio-inline { 122 | margin-right: 10px; 123 | } 124 | 125 | /* min and max displayed on top of sliders: https://github.com/rstudio/shiny/blob/master/inst/www/shared/ionrangeslider/css/ion.rangeSlider.skinHTML5.css */ 126 | .irs--shiny .irs-min, .irs--shiny .irs-max, .irs--shiny .irs-grid-text { 127 | color: #d9d9d9; 128 | } 129 | 130 | /* This is for the 'About' page: Restricting content width and styling the footer with the copyright */ 131 | .AboutContent { 132 | max-width: 1250px; 133 | margin: auto; 134 | border: none; 135 | padding: 30px; 136 | background-size: cover; 137 | margin-top: 0; 138 | } 139 | 140 | footer { 141 | color: #999; 142 | text-align: center; 143 | padding: 20px; 144 | } -------------------------------------------------------------------------------- /Course 7 - Web-Applications with Shiny in R/Full Apps/shiny-data-portal/www/logo.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SebKrantz/Data-Science-Programme/1f0ea0ea50a940f950b09e684e610aa684756ac6/Course 7 - Web-Applications with Shiny in R/Full Apps/shiny-data-portal/www/logo.png -------------------------------------------------------------------------------- /Course 7 - Web-Applications with Shiny in R/outputs.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SebKrantz/Data-Science-Programme/1f0ea0ea50a940f950b09e684e610aa684756ac6/Course 7 - Web-Applications with Shiny in R/outputs.png -------------------------------------------------------------------------------- /Course 7 - Web-Applications with Shiny in R/shiny.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SebKrantz/Data-Science-Programme/1f0ea0ea50a940f950b09e684e610aa684756ac6/Course 7 - Web-Applications with Shiny in R/shiny.pdf -------------------------------------------------------------------------------- /Course 7 - Web-Applications with Shiny in R/shiny.rstudio.com-tutorial/README.md: -------------------------------------------------------------------------------- 1 | # shiny.rstudio.com-tutorial 2 | 3 | This repository contains the slides and exercises for the video tutorial at https://shiny.rstudio.com/tutorial. You can either clone the repository or download its contents as a zipped folder by clicking on the green "Clone or download" button on the upper right corner. 4 | -------------------------------------------------------------------------------- /Course 7 - Web-Applications with Shiny in R/shiny.rstudio.com-tutorial/how-to-start-shiny-part-1.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SebKrantz/Data-Science-Programme/1f0ea0ea50a940f950b09e684e610aa684756ac6/Course 7 - Web-Applications with Shiny in R/shiny.rstudio.com-tutorial/how-to-start-shiny-part-1.pdf -------------------------------------------------------------------------------- /Course 7 - Web-Applications with Shiny in R/shiny.rstudio.com-tutorial/how-to-start-shiny-part-2.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SebKrantz/Data-Science-Programme/1f0ea0ea50a940f950b09e684e610aa684756ac6/Course 7 - Web-Applications with Shiny in R/shiny.rstudio.com-tutorial/how-to-start-shiny-part-2.pdf -------------------------------------------------------------------------------- /Course 7 - Web-Applications with Shiny in R/shiny.rstudio.com-tutorial/how-to-start-shiny-part-3.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SebKrantz/Data-Science-Programme/1f0ea0ea50a940f950b09e684e610aa684756ac6/Course 7 - Web-Applications with Shiny in R/shiny.rstudio.com-tutorial/how-to-start-shiny-part-3.pdf -------------------------------------------------------------------------------- /Course 7 - Web-Applications with Shiny in R/shiny.rstudio.com-tutorial/part-1-code/01-template.R: -------------------------------------------------------------------------------- 1 | library(shiny) 2 | ui <- fluidPage() 3 | 4 | server <- function(input, output) {} 5 | 6 | shinyApp(ui = ui, server = server) -------------------------------------------------------------------------------- /Course 7 - Web-Applications with Shiny in R/shiny.rstudio.com-tutorial/part-1-code/02-hist-app.R: -------------------------------------------------------------------------------- 1 | library(shiny) 2 | 3 | ui <- fluidPage( 4 | sliderInput(inputId = "num", 5 | label = "Choose a number", 6 | value = 25, min = 1, max = 100), 7 | plotOutput("hist") 8 | ) 9 | 10 | server <- function(input, output) { 11 | output$hist <- renderPlot({ 12 | hist(rnorm(input$num)) 13 | }) 14 | } 15 | 16 | shinyApp(ui = ui, server = server) -------------------------------------------------------------------------------- /Course 7 - Web-Applications with Shiny in R/shiny.rstudio.com-tutorial/part-1-code/app.R: -------------------------------------------------------------------------------- 1 | # 01-kmeans-app 2 | 3 | palette(c("#E41A1C", "#377EB8", "#4DAF4A", "#984EA3", 4 | "#FF7F00", "#FFFF33", "#A65628", "#F781BF", "#999999")) 5 | 6 | library(shiny) 7 | 8 | ui <- fluidPage( 9 | headerPanel('Iris k-means clustering'), 10 | sidebarPanel( 11 | selectInput('xcol', 'X Variable', names(iris)), 12 | selectInput('ycol', 'Y Variable', names(iris), 13 | selected = names(iris)[[2]]), 14 | numericInput('clusters', 'Cluster count', 3, 15 | min = 1, max = 9) 16 | ), 17 | mainPanel( 18 | plotOutput('plot1') 19 | ) 20 | ) 21 | 22 | server <- function(input, output) { 23 | 24 | selectedData <- reactive({ 25 | iris[, c(input$xcol, input$ycol)] 26 | }) 27 | 28 | clusters <- reactive({ 29 | kmeans(selectedData(), input$clusters) 30 | }) 31 | 32 | output$plot1 <- renderPlot({ 33 | par(mar = c(5.1, 4.1, 0, 1)) 34 | plot(selectedData(), 35 | col = clusters()$cluster, 36 | pch = 20, cex = 3) 37 | points(clusters()$centers, pch = 4, cex = 4, lwd = 4) 38 | }) 39 | 40 | } 41 | 42 | shinyApp(ui = ui, server = server) 43 | -------------------------------------------------------------------------------- /Course 7 - Web-Applications with Shiny in R/shiny.rstudio.com-tutorial/part-2-code/01-two-inputs.R: -------------------------------------------------------------------------------- 1 | # 01-two-inputs 2 | 3 | library(shiny) 4 | 5 | ui <- fluidPage( 6 | sliderInput(inputId = "num", 7 | label = "Choose a number", 8 | value = 25, min = 1, max = 100), 9 | textInput(inputId = "title", 10 | label = "Write a title", 11 | value = "Histogram of Random Normal Values"), 12 | plotOutput("hist") 13 | ) 14 | 15 | server <- function(input, output) { 16 | output$hist <- renderPlot({ 17 | hist(rnorm(input$num), main = input$title) 18 | }) 19 | } 20 | 21 | shinyApp(ui = ui, server = server) -------------------------------------------------------------------------------- /Course 7 - Web-Applications with Shiny in R/shiny.rstudio.com-tutorial/part-2-code/02-two-outputs.R: -------------------------------------------------------------------------------- 1 | # 02-two-outputs 2 | 3 | library(shiny) 4 | 5 | ui <- fluidPage( 6 | sliderInput(inputId = "num", 7 | label = "Choose a number", 8 | value = 25, min = 1, max = 100), 9 | plotOutput("hist"), 10 | verbatimTextOutput("stats") 11 | ) 12 | 13 | server <- function(input, output) { 14 | output$hist <- renderPlot({ 15 | hist(rnorm(input$num)) 16 | }) 17 | output$stats <- renderPrint({ 18 | summary(rnorm(input$num)) 19 | }) 20 | } 21 | 22 | shinyApp(ui = ui, server = server) -------------------------------------------------------------------------------- /Course 7 - Web-Applications with Shiny in R/shiny.rstudio.com-tutorial/part-2-code/03-reactive.R: -------------------------------------------------------------------------------- 1 | # 03-reactive 2 | 3 | library(shiny) 4 | 5 | ui <- fluidPage( 6 | sliderInput(inputId = "num", 7 | label = "Choose a number", 8 | value = 25, min = 1, max = 100), 9 | plotOutput("hist"), 10 | verbatimTextOutput("stats") 11 | ) 12 | 13 | server <- function(input, output) { 14 | 15 | data <- reactive({ 16 | rnorm(input$num) 17 | }) 18 | 19 | output$hist <- renderPlot({ 20 | hist(data()) 21 | }) 22 | output$stats <- renderPrint({ 23 | summary(data()) 24 | }) 25 | } 26 | 27 | shinyApp(ui = ui, server = server) -------------------------------------------------------------------------------- /Course 7 - Web-Applications with Shiny in R/shiny.rstudio.com-tutorial/part-2-code/04-isolate.R: -------------------------------------------------------------------------------- 1 | # 04-isolate 2 | 3 | library(shiny) 4 | 5 | ui <- fluidPage( 6 | sliderInput(inputId = "num", 7 | label = "Choose a number", 8 | value = 25, min = 1, max = 100), 9 | textInput(inputId = "title", 10 | label = "Write a title", 11 | value = "Histogram of Random Normal Values"), 12 | plotOutput("hist") 13 | ) 14 | 15 | server <- function(input, output) { 16 | output$hist <- renderPlot({ 17 | hist(rnorm(input$num), main = isolate(input$title)) 18 | }) 19 | } 20 | 21 | shinyApp(ui = ui, server = server) -------------------------------------------------------------------------------- /Course 7 - Web-Applications with Shiny in R/shiny.rstudio.com-tutorial/part-2-code/05-actionButton.R: -------------------------------------------------------------------------------- 1 | # 05-actionButton 2 | 3 | library(shiny) 4 | 5 | ui <- fluidPage( 6 | actionButton(inputId = "clicks", 7 | label = "Click me") 8 | ) 9 | 10 | server <- function(input, output) { 11 | observeEvent(input$clicks, { 12 | print(as.numeric(input$clicks)) 13 | }) 14 | } 15 | 16 | shinyApp(ui = ui, server = server) -------------------------------------------------------------------------------- /Course 7 - Web-Applications with Shiny in R/shiny.rstudio.com-tutorial/part-2-code/06-observeEvent.R: -------------------------------------------------------------------------------- 1 | # 06-observeEvent 2 | 3 | library(shiny) 4 | 5 | ui <- fluidPage( 6 | sliderInput(inputId = "num", 7 | label = "Choose a number", 8 | min = 1, max = 100, value = 25), 9 | actionButton(inputId = "go", 10 | label = "Print Value") 11 | ) 12 | 13 | server <- function(input, output) { 14 | 15 | # observe responds to the print button 16 | # but not the slider 17 | observeEvent(input$go, { 18 | print(as.numeric(input$num)) 19 | }) 20 | } 21 | 22 | shinyApp(ui = ui, server = server) -------------------------------------------------------------------------------- /Course 7 - Web-Applications with Shiny in R/shiny.rstudio.com-tutorial/part-2-code/07-eventReactive.R: -------------------------------------------------------------------------------- 1 | # 07-eventReactive 2 | 3 | library(shiny) 4 | 5 | ui <- fluidPage( 6 | sliderInput(inputId = "num", 7 | label = "Choose a number", 8 | value = 25, min = 1, max = 100), 9 | actionButton(inputId = "go", 10 | label = "Update"), 11 | plotOutput("hist") 12 | ) 13 | 14 | server <- function(input, output) { 15 | data <- eventReactive(input$go, { 16 | rnorm(input$num) 17 | }) 18 | 19 | output$hist <- renderPlot({ 20 | hist(data()) 21 | }) 22 | } 23 | 24 | shinyApp(ui = ui, server = server) 25 | -------------------------------------------------------------------------------- /Course 7 - Web-Applications with Shiny in R/shiny.rstudio.com-tutorial/part-2-code/08-reactiveValues.R: -------------------------------------------------------------------------------- 1 | # 08-reactiveValues 2 | 3 | library(shiny) 4 | 5 | ui <- fluidPage( 6 | actionButton(inputId = "norm", label = "Normal"), 7 | actionButton(inputId = "unif", label = "Uniform"), 8 | plotOutput("hist") 9 | ) 10 | 11 | server <- function(input, output) { 12 | 13 | rv <- reactiveValues(data = rnorm(100)) 14 | 15 | observeEvent(input$norm, { rv$data <- rnorm(100) }) 16 | observeEvent(input$unif, { rv$data <- runif(100) }) 17 | 18 | output$hist <- renderPlot({ 19 | hist(rv$data) 20 | }) 21 | } 22 | 23 | shinyApp(ui = ui, server = server) 24 | -------------------------------------------------------------------------------- /Course 7 - Web-Applications with Shiny in R/shiny.rstudio.com-tutorial/part-3-code/.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SebKrantz/Data-Science-Programme/1f0ea0ea50a940f950b09e684e610aa684756ac6/Course 7 - Web-Applications with Shiny in R/shiny.rstudio.com-tutorial/part-3-code/.DS_Store -------------------------------------------------------------------------------- /Course 7 - Web-Applications with Shiny in R/shiny.rstudio.com-tutorial/part-3-code/02-tags.R: -------------------------------------------------------------------------------- 1 | # 02-tags.R 2 | 3 | library(shiny) 4 | 5 | ui <- fluidPage( 6 | h1("My Shiny App"), 7 | p(style = "font-family:Impact", 8 | "See other apps in the", 9 | a("Shiny Showcase", 10 | href = "http://www.rstudio.com/ 11 | products/shiny/shiny-user-showcase/") 12 | ) 13 | ) 14 | 15 | server <- function(input, output){} 16 | 17 | shinyApp(ui = ui, server = server) -------------------------------------------------------------------------------- /Course 7 - Web-Applications with Shiny in R/shiny.rstudio.com-tutorial/part-3-code/03-layout.R: -------------------------------------------------------------------------------- 1 | # 03-layout.R 2 | 3 | library(shiny) 4 | 5 | ui <- fluidPage( 6 | fluidRow( 7 | column(3), 8 | column(5, sliderInput(inputId = "num", 9 | label = "Choose a number", 10 | value = 25, min = 1, max = 100)) 11 | ), 12 | fluidRow( 13 | column(4, offset = 8, 14 | plotOutput("hist") 15 | ) 16 | ) 17 | ) 18 | 19 | server <- function(input, output) { 20 | output$hist <- renderPlot({ 21 | hist(rnorm(input$num)) 22 | }) 23 | } 24 | 25 | shinyApp(ui = ui, server = server) -------------------------------------------------------------------------------- /Course 7 - Web-Applications with Shiny in R/shiny.rstudio.com-tutorial/part-3-code/04-well.R: -------------------------------------------------------------------------------- 1 | # 04-well.R 2 | 3 | library(shiny) 4 | 5 | ui <- fluidPage( 6 | wellPanel( 7 | sliderInput(inputId = "num", 8 | label = "Choose a number", 9 | value = 25, min = 1, max = 100), 10 | textInput(inputId = "title", 11 | label = "Write a title", 12 | value = "Histogram of Random Normal Values") 13 | ), 14 | plotOutput("hist") 15 | ) 16 | 17 | server <- function(input, output) { 18 | output$hist <- renderPlot({ 19 | hist(rnorm(input$num), main = input$title) 20 | }) 21 | } 22 | 23 | shinyApp(ui = ui, server = server) -------------------------------------------------------------------------------- /Course 7 - Web-Applications with Shiny in R/shiny.rstudio.com-tutorial/part-3-code/05-tabs.R: -------------------------------------------------------------------------------- 1 | # 05-tabs.R 2 | 3 | library(shiny) 4 | 5 | ui <- fluidPage(title = "Random generator", 6 | tabsetPanel( 7 | tabPanel(title = "Normal data", 8 | plotOutput("norm"), 9 | actionButton("renorm", "Resample") 10 | ), 11 | tabPanel(title = "Uniform data", 12 | plotOutput("unif"), 13 | actionButton("reunif", "Resample") 14 | ), 15 | tabPanel(title = "Chi Squared data", 16 | plotOutput("chisq"), 17 | actionButton("rechisq", "Resample") 18 | ) 19 | ) 20 | ) 21 | 22 | server <- function(input, output) { 23 | 24 | rv <- reactiveValues( 25 | norm = rnorm(500), 26 | unif = runif(500), 27 | chisq = rchisq(500, 2)) 28 | 29 | observeEvent(input$renorm, { rv$norm <- rnorm(500) }) 30 | observeEvent(input$reunif, { rv$unif <- runif(500) }) 31 | observeEvent(input$rechisq, { rv$chisq <- rchisq(500, 2) }) 32 | 33 | output$norm <- renderPlot({ 34 | hist(rv$norm, breaks = 30, col = "grey", border = "white", 35 | main = "500 random draws from a standard normal distribution") 36 | }) 37 | output$unif <- renderPlot({ 38 | hist(rv$unif, breaks = 30, col = "grey", border = "white", 39 | main = "500 random draws from a standard uniform distribution") 40 | }) 41 | output$chisq <- renderPlot({ 42 | hist(rv$chisq, breaks = 30, col = "grey", border = "white", 43 | main = "500 random draws from a Chi Square distribution with two degree of freedom") 44 | }) 45 | } 46 | 47 | shinyApp(server = server, ui = ui) -------------------------------------------------------------------------------- /Course 7 - Web-Applications with Shiny in R/shiny.rstudio.com-tutorial/part-3-code/06-navlist.R: -------------------------------------------------------------------------------- 1 | # 06-navlist.R 2 | 3 | library(shiny) 4 | 5 | ui <- fluidPage(title = "Random generator", 6 | navlistPanel( 7 | tabPanel(title = "Normal data", 8 | plotOutput("norm"), 9 | actionButton("renorm", "Resample") 10 | ), 11 | tabPanel(title = "Uniform data", 12 | plotOutput("unif"), 13 | actionButton("reunif", "Resample") 14 | ), 15 | tabPanel(title = "Chi Squared data", 16 | plotOutput("chisq"), 17 | actionButton("rechisq", "Resample") 18 | ) 19 | ) 20 | ) 21 | 22 | server <- function(input, output) { 23 | 24 | rv <- reactiveValues( 25 | norm = rnorm(500), 26 | unif = runif(500), 27 | chisq = rchisq(500, 2)) 28 | 29 | observeEvent(input$renorm, { rv$norm <- rnorm(500) }) 30 | observeEvent(input$reunif, { rv$unif <- runif(500) }) 31 | observeEvent(input$rechisq, { rv$chisq <- rchisq(500, 2) }) 32 | 33 | output$norm <- renderPlot({ 34 | hist(rv$norm, breaks = 30, col = "grey", border = "white", 35 | main = "500 random draws from a standard normal distribution") 36 | }) 37 | output$unif <- renderPlot({ 38 | hist(rv$unif, breaks = 30, col = "grey", border = "white", 39 | main = "500 random draws from a standard uniform distribution") 40 | }) 41 | output$chisq <- renderPlot({ 42 | hist(rv$chisq, breaks = 30, col = "grey", border = "white", 43 | main = "500 random draws from a Chi Square distribution with two degree of freedom") 44 | }) 45 | } 46 | 47 | shinyApp(server = server, ui = ui) -------------------------------------------------------------------------------- /Course 7 - Web-Applications with Shiny in R/shiny.rstudio.com-tutorial/part-3-code/07-sidebar.R: -------------------------------------------------------------------------------- 1 | # 04-well.R 2 | 3 | library(shiny) 4 | 5 | ui <- fluidPage( 6 | sidebarLayout( 7 | sidebarPanel( 8 | sliderInput(inputId = "num", 9 | label = "Choose a number", 10 | value = 25, min = 1, max = 100), 11 | textInput(inputId = "title", 12 | label = "Write a title", 13 | value = "Histogram of Random Normal Values") 14 | ), 15 | mainPanel( 16 | plotOutput("hist") 17 | ) 18 | ) 19 | ) 20 | 21 | server <- function(input, output) { 22 | output$hist <- renderPlot({ 23 | hist(rnorm(input$num), main = input$title) 24 | }) 25 | } 26 | 27 | shinyApp(ui = ui, server = server) -------------------------------------------------------------------------------- /Course 7 - Web-Applications with Shiny in R/shiny.rstudio.com-tutorial/part-3-code/08-navbarPage.R: -------------------------------------------------------------------------------- 1 | # 06-navlist.R 2 | 3 | library(shiny) 4 | 5 | ui <- navbarPage(title = "Random generator", 6 | tabPanel(title = "Normal data", 7 | plotOutput("norm"), 8 | actionButton("renorm", "Resample") 9 | ), 10 | tabPanel(title = "Uniform data", 11 | plotOutput("unif"), 12 | actionButton("reunif", "Resample") 13 | ), 14 | tabPanel(title = "Chi Squared data", 15 | plotOutput("chisq"), 16 | actionButton("rechisq", "Resample") 17 | ) 18 | 19 | ) 20 | 21 | server <- function(input, output) { 22 | 23 | rv <- reactiveValues( 24 | norm = rnorm(500), 25 | unif = runif(500), 26 | chisq = rchisq(500, 2)) 27 | 28 | observeEvent(input$renorm, { rv$norm <- rnorm(500) }) 29 | observeEvent(input$reunif, { rv$unif <- runif(500) }) 30 | observeEvent(input$rechisq, { rv$chisq <- rchisq(500, 2) }) 31 | 32 | output$norm <- renderPlot({ 33 | hist(rv$norm, breaks = 30, col = "grey", border = "white", 34 | main = "500 random draws from a standard normal distribution") 35 | }) 36 | output$unif <- renderPlot({ 37 | hist(rv$unif, breaks = 30, col = "grey", border = "white", 38 | main = "500 random draws from a standard uniform distribution") 39 | }) 40 | output$chisq <- renderPlot({ 41 | hist(rv$chisq, breaks = 30, col = "grey", border = "white", 42 | main = "500 random draws from a Chi Square distribution with two degree of freedom") 43 | }) 44 | } 45 | 46 | shinyApp(server = server, ui = ui) -------------------------------------------------------------------------------- /Course 7 - Web-Applications with Shiny in R/shiny.rstudio.com-tutorial/part-3-code/09-navbarMenu.R: -------------------------------------------------------------------------------- 1 | # 06-navlist.R 2 | 3 | library(shiny) 4 | 5 | ui <- navbarPage(title = "Random generator", 6 | tabPanel(title = "Normal data", 7 | plotOutput("norm"), 8 | actionButton("renorm", "Resample") 9 | ), 10 | navbarMenu(title = "Other data", 11 | tabPanel(title = "Uniform data", 12 | plotOutput("unif"), 13 | actionButton("reunif", "Resample") 14 | ), 15 | tabPanel(title = "Chi Squared data", 16 | plotOutput("chisq"), 17 | actionButton("rechisq", "Resample") 18 | ) 19 | ) 20 | ) 21 | 22 | server <- function(input, output) { 23 | 24 | rv <- reactiveValues( 25 | norm = rnorm(500), 26 | unif = runif(500), 27 | chisq = rchisq(500, 2)) 28 | 29 | observeEvent(input$renorm, { rv$norm <- rnorm(500) }) 30 | observeEvent(input$reunif, { rv$unif <- runif(500) }) 31 | observeEvent(input$rechisq, { rv$chisq <- rchisq(500, 2) }) 32 | 33 | output$norm <- renderPlot({ 34 | hist(rv$norm, breaks = 30, col = "grey", border = "white", 35 | main = "500 random draws from a standard normal distribution") 36 | }) 37 | output$unif <- renderPlot({ 38 | hist(rv$unif, breaks = 30, col = "grey", border = "white", 39 | main = "500 random draws from a standard uniform distribution") 40 | }) 41 | output$chisq <- renderPlot({ 42 | hist(rv$chisq, breaks = 30, col = "grey", border = "white", 43 | main = "500 random draws from a Chi Square distribution with two degree of freedom") 44 | }) 45 | } 46 | 47 | shinyApp(server = server, ui = ui) -------------------------------------------------------------------------------- /Course 7 - Web-Applications with Shiny in R/shiny.rstudio.com-tutorial/part-3-code/App-Directory/.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SebKrantz/Data-Science-Programme/1f0ea0ea50a940f950b09e684e610aa684756ac6/Course 7 - Web-Applications with Shiny in R/shiny.rstudio.com-tutorial/part-3-code/App-Directory/.DS_Store -------------------------------------------------------------------------------- /Course 7 - Web-Applications with Shiny in R/shiny.rstudio.com-tutorial/part-3-code/App-Directory/app.R: -------------------------------------------------------------------------------- 1 | library(shiny) 2 | 3 | ui <- fluidPage( 4 | tags$img(height = 100, 5 | width = 100, 6 | src = "bigorb.png") 7 | ) 8 | 9 | server <- function(input, output){} 10 | shinyApp(ui = ui, server = server) -------------------------------------------------------------------------------- /Course 7 - Web-Applications with Shiny in R/shiny.rstudio.com-tutorial/part-3-code/App-Directory/www/bigorb.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SebKrantz/Data-Science-Programme/1f0ea0ea50a940f950b09e684e610aa684756ac6/Course 7 - Web-Applications with Shiny in R/shiny.rstudio.com-tutorial/part-3-code/App-Directory/www/bigorb.png -------------------------------------------------------------------------------- /Data Science Programme Flyer.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SebKrantz/Data-Science-Programme/1f0ea0ea50a940f950b09e684e610aa684756ac6/Data Science Programme Flyer.jpg -------------------------------------------------------------------------------- /Data-Science-Programme.Rproj: -------------------------------------------------------------------------------- 1 | Version: 1.0 2 | 3 | RestoreWorkspace: Default 4 | SaveWorkspace: Default 5 | AlwaysSaveHistory: Default 6 | 7 | EnableCodeIndexing: Yes 8 | UseSpacesForTab: Yes 9 | NumSpacesForTab: 2 10 | Encoding: UTF-8 11 | 12 | RnwWeave: knitr 13 | LaTeX: pdfLaTeX 14 | -------------------------------------------------------------------------------- /General Information and Further Resources/Course Introduction Presentation/DS.PNG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SebKrantz/Data-Science-Programme/1f0ea0ea50a940f950b09e684e610aa684756ac6/General Information and Further Resources/Course Introduction Presentation/DS.PNG -------------------------------------------------------------------------------- /General Information and Further Resources/Course Introduction Presentation/General-Information-and-Further-Resources.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SebKrantz/Data-Science-Programme/1f0ea0ea50a940f950b09e684e610aa684756ac6/General Information and Further Resources/Course Introduction Presentation/General-Information-and-Further-Resources.pdf -------------------------------------------------------------------------------- /General Information and Further Resources/Course Introduction Presentation/IMG_2155.PNG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SebKrantz/Data-Science-Programme/1f0ea0ea50a940f950b09e684e610aa684756ac6/General Information and Further Resources/Course Introduction Presentation/IMG_2155.PNG -------------------------------------------------------------------------------- /General Information and Further Resources/Course Introduction Presentation/data-science.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SebKrantz/Data-Science-Programme/1f0ea0ea50a940f950b09e684e610aa684756ac6/General Information and Further Resources/Course Introduction Presentation/data-science.png -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Data Science Programme 2 | R based data science training delivered to the Ugandan Ministry of Finance and Bureau of Statistics. 3 | 4 | -------------------------------------------------------------------------------- /Setup SSH Access on Github.R: -------------------------------------------------------------------------------- 1 | # Source: https://happygitwithr.com/hello-git.html 2 | # After creating a project with version control, using an existing or newly created Github repository, 3 | # in Rstudio under Git click 'More' and then 'Shell', Execute the following commands: 4 | 5 | bash # gets git bash shell 6 | 7 | # Create user: 8 | git config --global user.name 'Jane Doe' 9 | git config --global user.email 'jane@example.com' 10 | git config --global --list 11 | 12 | # https://happygitwithr.com/ssh-keys.html 13 | 14 | ls -al ~/.ssh/ # If you see a pair of files like id_rsa.pub and id_rsa, you have a key pair already. 15 | # In Rstudio Go to Tools > Global Options…> Git/SVN > Create RSA Key…. 16 | # Click “Create” and RStudio will generate an SSH key pair, stored in the files ~/.ssh/id_rsa and ~/.ssh/id_rsa.pub 17 | 18 | # then in R, open shell, do 19 | eval $(ssh-agent -s) 20 | ssh-add ~/.ssh/id_rsa 21 | 22 | # finally (windows specific): 23 | git config remote.origin.url git@github.com:your_username/your_project.git 24 | 25 | # Now we store a copy of your public key on GitHub. 26 | # In Rstudio Go to Tools > Global Options…> Git/SVN. If your key pair has the usual name, id_rsa.pub and id_rsa, 27 | # RStudio will see it and offer to “View public key”. Do that and accept the offer to copy to your clipboard. 28 | # If your key pair is named differently, use another method. 29 | 30 | # Make sure you’re signed into GitHub. Click on your profile pic in upper right corner and go Settings, 31 | # then SSH and GPG keys. Click “New SSH key”. Paste your public key in the “Key” box. Give it an informative title, 32 | # presumably related to the comment you used above, during key creation. For example, you might use 2018-mbp to 33 | # record the year and computer. Click “Add SSH key”. 34 | 35 | # In theory, we’re done! You can use 36 | ssh -T git@github.com 37 | # to test your connection to GitHub. 38 | # If you’re not sure what to make of the output, see the link for details. Of course, 39 | # the best test is to work through the realistic usage examples elsewhere in this guide. 40 | 41 | 42 | # Note also: For each new github repository (Project in Rstudio), 43 | # you again need to enable SSH by executing these commands again in the git bash shell. 44 | 45 | bash # Get git bash command line 46 | 47 | # Adding SSH 48 | eval $(ssh-agent -s) 49 | ssh-add ~/.ssh/id_rsa # Type your password after executing this. 50 | # And (only on Windows): 51 | git config remote.origin.url git@github.com:your_username/your_project.git 52 | --------------------------------------------------------------------------------