S3729C Wellness and Health Management - Lesson 14
Class Date : 24 September 2022
At the end of this lesson, students will be able to:
GitHub Link : https://github.com/aaron-chen-angus/S3729C-Lesson-Files/blob/main/MoviesPrime.R
You can run the source code (also extracted below) in your R Studio Cloud workspace. NOTE : The output below does not show the final functional app as it needs to be run in R Studio Cloud (hence ignore the warning messages below).
# Load packages ----------------------------------------------------------------
library(shiny)
library(shinythemes)
library(ggplot2)
library(tools)
library(DT)##
## Attaching package: 'DT'
## The following objects are masked from 'package:shiny':
##
## dataTableOutput, renderDataTable
# Load data --------------------------------------------------------------------
movies <- read.csv(file = "https://raw.githubusercontent.com/aaron-chen-angus/S3729C-Lesson-Files/6a58d56d3d42231fb011af462db7efc01537e515/movies.csv", header = TRUE, sep = ",")
all_studios <- sort(unique(movies$studio))
min_date <- min(as.numeric(as.character(movies$thtr_rel_date)))## Warning: NAs introduced by coercion
## Warning: NAs introduced by coercion
# Define UI --------------------------------------------------------------------
ui <- fluidPage(theme = shinytheme("simplex"),
h1("Movies Database Viewer for S3729C"),
h4(tags$a(href = "https://shiny.rstudio.com/", "Powered by R Shiny")),
sidebarLayout(
sidebarPanel(
HTML(paste0("Movies released between the following dates will be plotted.")),
br(), br(),
dateRangeInput(
inputId = "date",
label = "Select dates:",
start = "2013-01-01", end = "2014-01-01",
min = min_date, max = max_date,
startview = "year"
),
selectInput(
inputId = "y",
label = "Y-axis:",
choices = c(
"IMDB rating" = "imdb_rating",
"IMDB number of votes" = "imdb_num_votes",
"Critics Score" = "critics_score",
"Audience Score" = "audience_score",
"Runtime" = "runtime"
),
selected = "audience_score"
),
selectInput(
inputId = "x",
label = "X-axis:",
choices = c(
"IMDB rating" = "imdb_rating",
"IMDB number of votes" = "imdb_num_votes",
"Critics Score" = "critics_score",
"Audience Score" = "audience_score",
"Runtime" = "runtime"
),
selected = "critics_score"
),
selectInput(
inputId = "z",
label = "Color by:",
choices = c(
"Title Type" = "title_type",
"Genre" = "genre",
"MPAA Rating" = "mpaa_rating",
"Critics Rating" = "critics_rating",
"Audience Rating" = "audience_rating"
),
selected = "mpaa_rating"
),
sliderInput(
inputId = "alpha",
label = "Alpha:",
min = 0, max = 1,
value = 0.5
),
sliderInput(
inputId = "size",
label = "Size:",
min = 0, max = 5,
value = 2
),
textInput(
inputId = "plot_title",
label = "Plot title",
placeholder = "Enter text to be used as plot title"
),
actionButton(
inputId = "update_plot_title",
label = "Update plot title"
),
br(), br(),
selectInput(
inputId = "studio",
label = "Select the Movie Studio:",
choices = all_studios,
selected = "20th Century Fox",
multiple = TRUE
),
downloadButton('download',"Download data")
),
mainPanel(
plotOutput(outputId = "scatterplot", hover = "plot_hover"),
dataTableOutput(outputId = "moviestablehover"),
br(),
dataTableOutput(outputId = "moviestable")
)
)
)## Warning: Couldn't coerce the `min` argument to a date string with format yyyy-
## mm-dd
## Warning: Couldn't coerce the `max` argument to a date string with format yyyy-
## mm-dd
# Define server ----------------------------------------------------------------
server <- function(input, output, session) {
new_plot_title <- eventReactive(
eventExpr = input$update_plot_title,
valueExpr = {
toTitleCase(input$plot_title)
}
)
output$scatterplot <- renderPlot({
req(input$date)
movies_selected_date <- movies %>%
filter(thtr_rel_date >= as.POSIXct(input$date[1]) & thtr_rel_date <= as.POSIXct(input$date[2]))
ggplot(data = movies, aes_string(x = input$x, y = input$y, color = input$z)) +
geom_point(alpha = input$alpha, size = input$size) +
labs(title = new_plot_title())
})
output$moviestablehover <- renderDataTable({
nearPoints(movies, input$plot_hover) %>%
select(title, thtr_rel_year, title_type, genre, runtime, mpaa_rating, studio, director)
})
output$moviestable <- renderDataTable({
req(input$studio)
movies_from_selected_studios <- movies %>%
filter(studio %in% input$studio) %>%
select(title:studio)
DT::datatable(
data = movies_from_selected_studios,
options = list(pageLength = 10),
rownames = FALSE)
})
}
# Create the Shiny app object --------------------------------------------------
shinyApp(ui = ui, server = server)##
## Listening on http://127.0.0.1:5142
## Warning: Error in filter: object 'thtr_rel_date' not found
## Warning: Error in select: could not find function "select"
## Warning: Error in select: could not find function "select"
GitHub Link : https://github.com/aaron-chen-angus/S3729C-Lesson-Files/blob/main/COVID19vis.R
You can run the source code below in your R Studio Cloud workspace.
# Load packages ----------------------------------------------------------------
library(shiny)
library(plotly)##
## Attaching package: 'plotly'
## The following object is masked from 'package:ggplot2':
##
## last_plot
## The following object is masked from 'package:stats':
##
## filter
## The following object is masked from 'package:graphics':
##
## layout
library(COVID19)
# Define UI --------------------------------------------------------------------
ui <- fluidPage(
selectInput("country", label = "Country", multiple = TRUE, choices = unique(covid19()$administrative_area_level_1), selected = "Singapore"),
selectInput("type", label = "type", choices = c("confirmed", "tests", "recovered", "deaths")),
selectInput("level", label = "Granularity", choices = c("Country" = 1, "Region" = 2, "City" = 3), selected = 1),
dateRangeInput("date", label = "Date", start = "2020-01-01"),
plotlyOutput("covid19plot")
)
# Define server ----------------------------------------------------------------
server <- function(input, output) {
output$covid19plot <- renderPlotly({
if(!is.null(input$country)){
x <- covid19(country = input$country, level = input$level, start = input$date[1], end = input$date[2])
color <- paste0("administrative_area_level_", input$level)
plot_ly(x = x[["date"]], y = x[[input$type]], color = x[[color]])
}
})
}
# Create the Shiny app object --------------------------------------------------
shinyApp(ui = ui, server = server)##
## Listening on http://127.0.0.1:6897
## No trace type specified:
## Based on info supplied, a 'scatter' trace seems appropriate.
## Read more about this trace type -> https://plotly.com/r/reference/#scatter
## No scatter mode specifed:
## Setting the mode to markers
## Read more about this attribute -> https://plotly.com/r/reference/#scatter-mode
## Warning: Ignoring 1 observations
## Warning in RColorBrewer::brewer.pal(N, "Set2"): minimal value for n is 3, returning requested palette with 3 different levels
## Warning in RColorBrewer::brewer.pal(N, "Set2"): minimal value for n is 3, returning requested palette with 3 different levels
GitHub Link : https://github.com/aaron-chen-angus/S3729C-Lesson-Files/blob/main/BMIcalculator.R
You can run the source code below in your R Studio Cloud workspace.
# Load packages ----------------------------------------------------------------
library(shiny)
library(shinythemes)
# Define UI --------------------------------------------------------------------
ui <- fluidPage(theme = shinytheme("united"),
navbarPage("BMI Calculator:",
tabPanel("Home",
# Input values
sidebarPanel(
HTML("<h3>Input parameters</h3>"),
sliderInput("height",
label = "Height in cm",
value = 185,
min = 40,
max = 250),
sliderInput("weight",
label = "Weight in kg",
value = 88,
min = 40,
max = 120),
actionButton("submitbutton",
"Submit",
class = "btn btn-primary")
),
mainPanel(
tags$label(h3('Status/Output')), # Status/Output Text Box
verbatimTextOutput('contents'),
tableOutput('tabledata') # Results table
) # mainPanel()
), #tabPanel(), Home
tabPanel("About",
titlePanel("About"),
p("Body Mass Index (BMI) is essentially a value obtained from the weight and height of a person [1]."),
br(),
strong("Calculating the BMI"),
p("BMI can be computed by dividing the person's weight (kg) by their squared height (m) as follows:"),
p("BMI = kg/m^2"),
p("where",
span("kg", style = "color:blue"),
"represents the person's weight and",
span("m^2", style = "color:blue"),
"the person's squared height."),
br(),
strong("Take Note"),
p("This BMI Calculator is for adults 20 years and older. Further information on calculating BMI for children and teenagers is available from the CDC [2]."),
br(),
strong("References"),
p("1. Centers for Disease Control. [Body Mass Index (BMI)](https://www.cdc.gov/healthyweight/assessing/bmi/index.html), Accessed September 13, 2022."),
p("2. Centers for Disease Control. [BMI Percentile Calculator for Child and Teen](https://www.cdc.gov/healthyweight/bmi/calculator.html), Accessed September 13, 2022.")
) #tabPanel(), About
) # navbarPage()
) # fluidPage()
# Define server ----------------------------------------------------------------
server <- function(input, output, session) {
# Input Data
datasetInput <- reactive({
bmi <- input$weight/( (input$height/100) * (input$height/100) )
bmi <- data.frame(bmi)
names(bmi) <- "BMI"
print(bmi)
})
# Status/Output Text Box
output$contents <- renderPrint({
if (input$submitbutton>0) {
isolate("Calculation of BMI complete.")
} else {
return("Press submit after you have selected your height and weight using the sliders.")
}
})
# Prediction results table
output$tabledata <- renderTable({
if (input$submitbutton>0) {
isolate(datasetInput())
}
})
}
# Create a Shiny app object ----------------------------------------------------
shinyApp(ui = ui, server = server)##
## Listening on http://127.0.0.1:7819
GitHub Link : https://github.com/aaron-chen-angus/S3729C-Lesson-Files/blob/main/WordCloud.R
You can run the source code below in your R Studio Cloud workspace.
# Load packages ----------------------------------------------------------------
library(shiny)
library(shinythemes)
library(wordcloud2)
library(tm)## Loading required package: NLP
##
## Attaching package: 'NLP'
## The following object is masked from 'package:ggplot2':
##
## annotate
##
## Attaching package: 'colourpicker'
## The following object is masked from 'package:shiny':
##
## runExample
# Define UI --------------------------------------------------------------------
ui <- fluidPage(theme = shinytheme("flatly"),
h1("Word Cloud Generator"),
h4(tags$a(href = "https://shiny.rstudio.com/", "Powered by R Shiny")),
# Create a container for tab panels
tabsetPanel(
# Create a "Word cloud" tab
tabPanel(
title = "Word cloud",
sidebarLayout(
sidebarPanel(
radioButtons(
inputId = "source",
label = "Word source",
choices = c(
"Dynamite by BTS" = "lyrics",
"Use your own words" = "own",
"Upload a file" = "file"
)
),
hr(),
# Add the selector for the language of the text
selectInput(
inputId = "language",
label = "Remove stopwords in",
choices = c("Danish", "Dutch", "English", "Finnish", "French", "German", "Hungarian", "Italian", "Norwegian", "Portuguese", "Russian", "Spanish", "Swedish"),
multiple = FALSE,
selected = "English"
),
conditionalPanel(
condition = "input.source == 'own'",
textAreaInput("text", "Enter text", rows = 7)
),
# Wrap the file input in a conditional panel
conditionalPanel(
# The condition should be that the user selects
# "file" from the radio buttons
condition = "input.source == 'file'",
fileInput("file", "Select a file")
),
hr(),
checkboxInput("remove_words", "Remove specific words?", FALSE),
conditionalPanel(
condition = "input.remove_words == 1",
textAreaInput("words_to_remove1", "Words to remove (one per line)", rows = 1)
),
conditionalPanel(
condition = "input.remove_words == 1 && input.words_to_remove1.length > 0",
textAreaInput("words_to_remove2", "", rows = 1)
),
conditionalPanel(
condition = "input.remove_words == 1 && input.words_to_remove2.length > 0",
textAreaInput("words_to_remove3", "", rows = 1)
),
conditionalPanel(
condition = "input.remove_words == 1 && input.words_to_remove3.length > 0",
textAreaInput("words_to_remove4", "", rows = 1)
),
conditionalPanel(
condition = "input.remove_words == 1 && input.words_to_remove4.length > 0",
textAreaInput("words_to_remove5", "", rows = 1)
),
conditionalPanel(
condition = "input.remove_words == 1 && input.words_to_remove5.length > 0",
textAreaInput("words_to_remove6", "", rows = 1)
),
conditionalPanel(
condition = "input.remove_words == 1 && input.words_to_remove6.length > 0",
textAreaInput("words_to_remove7", "", rows = 1)
),
conditionalPanel(
condition = "input.remove_words == 1 && input.words_to_remove7.length > 0",
textAreaInput("words_to_remove8", "", rows = 1)
),
conditionalPanel(
condition = "input.remove_words == 1 && input.words_to_remove8.length > 0",
textAreaInput("words_to_remove9", "", rows = 1)
),
conditionalPanel(
condition = "input.remove_words == 1 && input.words_to_remove9.length > 0",
textAreaInput("words_to_remove10", "", rows = 1)
),
hr(),
numericInput("num", "Maximum number of words",
value = 100, min = 5
),
hr(),
colourInput("col", "Background color", value = "white"),
hr(),
HTML('<p>This is an app created using <a href="https://shiny.rstudio.com/">R Shiny</a> for S3729C Lesson 14.</p>')
),
mainPanel(
wordcloud2Output("cloud"),
# br(),
# br(),
# tags$a(href="https://shiny.rstudio.com/", "Learn more at shiny.rstudio.com"),
br(),
br()
)
)
),
# Create an "About this app" tab
tabPanel(
title = "About this app",
br(),
"Instructions on how to use this Shiny app:",
br(),
br(),
HTML("<ul><li>When uploading a file, make sure to upload a .csv or .txt file</li>
<li>If it is a .csv file, there should be only one column containing all words or sentences (see below for example files)</li>
<li>Numbers and punctuations will be automatically removed, as well as stop words in the language of your choice (via the dropdown selector)</li></ul>"),
"Example files:",
tags$a(href = "https://raw.githubusercontent.com/aaron-chen-angus/S3729C-Lesson-Files/main/Dynamite.csv", "example.csv"),
"and",
tags$a(href = "https://raw.githubusercontent.com/aaron-chen-angus/S3729C-Lesson-Files/main/Dynamite.txt", "example.txt"),
br(),
br(),
em("Created Using : R Shiny"),
br(),
br(),
HTML('<p>This is an app created using <a href="https://shiny.rstudio.com/">R Shiny</a> for S3729C Lesson 14.</p>'),
br(),
br()
)
)
)
# Define server ----------------------------------------------------------------
server <- function(input, output) {
data_source <- reactive({
if (input$source == "lyrics") {
data <- read.csv("https://raw.githubusercontent.com/aaron-chen-angus/S3729C-Lesson-Files/main/Dynamite.csv",
sep = "&",
stringsAsFactors = FALSE
)
data <- data[, 1]
} else if (input$source == "own") {
data <- input$text
} else if (input$source == "file") {
data <- input_file()
}
return(data)
})
input_file <- reactive({
if (is.null(input$file)) {
return("")
}
readLines(input$file$datapath)
})
create_wordcloud <- function(data, num_words = 100, background = "white") {
# If text is provided, convert it to a dataframe of word frequencies
if (is.character(data)) {
corpus <- Corpus(VectorSource(data))
corpus <- tm_map(corpus, tolower)
corpus <- tm_map(corpus, removePunctuation)
corpus <- tm_map(corpus, removeNumbers)
corpus <- tm_map(corpus, removeWords, stopwords(tolower(input$language)))
corpus <- tm_map(corpus, removeWords, c(input$words_to_remove1))
corpus <- tm_map(corpus, removeWords, c(input$words_to_remove2))
corpus <- tm_map(corpus, removeWords, c(input$words_to_remove3))
corpus <- tm_map(corpus, removeWords, c(input$words_to_remove4))
corpus <- tm_map(corpus, removeWords, c(input$words_to_remove5))
corpus <- tm_map(corpus, removeWords, c(input$words_to_remove6))
corpus <- tm_map(corpus, removeWords, c(input$words_to_remove7))
corpus <- tm_map(corpus, removeWords, c(input$words_to_remove8))
corpus <- tm_map(corpus, removeWords, c(input$words_to_remove9))
corpus <- tm_map(corpus, removeWords, c(input$words_to_remove10))
tdm <- as.matrix(TermDocumentMatrix(corpus))
data <- sort(rowSums(tdm), decreasing = TRUE)
data <- data.frame(word = names(data), freq = as.numeric(data))
}
# Make sure a proper num_words is provided
if (!is.numeric(num_words) || num_words < 3) {
num_words <- 3
}
# Grab the top n most common words
data <- head(data, n = num_words)
if (nrow(data) == 0) {
return(NULL)
}
wordcloud2(data, backgroundColor = background)
}
output$cloud <- renderWordcloud2({
create_wordcloud(data_source(),
num_words = input$num,
background = input$col
)
})
}
# Create the Shiny app object --------------------------------------------------
shinyApp(ui = ui, server = server)##
## Listening on http://127.0.0.1:6141
## Warning in tm_map.SimpleCorpus(corpus, tolower): transformation drops documents
## Warning in tm_map.SimpleCorpus(corpus, removePunctuation): transformation drops
## documents
## Warning in tm_map.SimpleCorpus(corpus, removeNumbers): transformation drops
## documents
## Warning in tm_map.SimpleCorpus(corpus, removeWords,
## stopwords(tolower(input$language))): transformation drops documents
## Warning in tm_map.SimpleCorpus(corpus, removeWords, c(input$words_to_remove1)):
## transformation drops documents
## Warning in tm_map.SimpleCorpus(corpus, removeWords, c(input$words_to_remove2)):
## transformation drops documents
## Warning in tm_map.SimpleCorpus(corpus, removeWords, c(input$words_to_remove3)):
## transformation drops documents
## Warning in tm_map.SimpleCorpus(corpus, removeWords, c(input$words_to_remove4)):
## transformation drops documents
## Warning in tm_map.SimpleCorpus(corpus, removeWords, c(input$words_to_remove5)):
## transformation drops documents
## Warning in tm_map.SimpleCorpus(corpus, removeWords, c(input$words_to_remove6)):
## transformation drops documents
## Warning in tm_map.SimpleCorpus(corpus, removeWords, c(input$words_to_remove7)):
## transformation drops documents
## Warning in tm_map.SimpleCorpus(corpus, removeWords, c(input$words_to_remove8)):
## transformation drops documents
## Warning in tm_map.SimpleCorpus(corpus, removeWords, c(input$words_to_remove9)):
## transformation drops documents
## Warning in tm_map.SimpleCorpus(corpus, removeWords, c(input$words_to_remove10)):
## transformation drops documents
GitHub Link : https://github.com/aaron-chen-angus/S3729C-Lesson-Files/blob/main/UFCdashboard.R
You can run the source code below in your R Studio Cloud workspace.
# Load packages ----------------------------------------------------------------
library(shiny)
library(tidyverse)## ── Attaching packages ─────────────────────────────────────── tidyverse 1.3.2 ──
## ✔ tibble 3.1.8 ✔ dplyr 1.0.10
## ✔ tidyr 1.2.0 ✔ stringr 1.4.1
## ✔ readr 2.1.2 ✔ forcats 0.5.2
## ✔ purrr 0.3.4
## ── Conflicts ────────────────────────────────────────── tidyverse_conflicts() ──
## ✖ NLP::annotate() masks ggplot2::annotate()
## ✖ dplyr::filter() masks plotly::filter(), stats::filter()
## ✖ dplyr::lag() masks stats::lag()
##
## Attaching package: 'shinydashboard'
##
## The following object is masked from 'package:graphics':
##
## box
# Load data --------------------------------------------------------------------
elo_df <- read.csv(file = "https://raw.githubusercontent.com/aaron-chen-angus/S3729C-Lesson-Files/main/elo_df.csv", header = TRUE, sep = ",")
df <- read.csv(file = "https://raw.githubusercontent.com/aaron-chen-angus/S3729C-Lesson-Files/main/elo.csv", header = TRUE, sep = ",")
create_elo_data <- function(k){
temp_df <- elo.run(winner ~ fighter + opponent, k = k,
data = elo_df %>% arrange(fighter , date)) %>%
as_tibble() %>%
cbind(elo_df %>% arrange(fighter, date) %>% select(match_id)) %>%
select(team.A, team.B, elo.A, elo.B, match_id)
rbind(temp_df %>%
select_at(vars(contains(".A"), contains("match_id"))) %>%
rename_all(.funs = function(x) str_replace(x, ".A", "")),
temp_df %>%
select_at(vars(contains(".B"), contains("match_id"))) %>%
rename_all(.funs = function(x) str_replace(x, ".B", ""))) %>%
rename("fighter" = "team") %>%
left_join(df %>%
select(fighter, date, weight_class, match_id),
by = c("fighter", "match_id")) %>%
mutate(date = as.Date(date))
}
create_elo_data(20) %>% colnames()
# Define UI --------------------------------------------------------------------
ui <- dashboardPage(
dashboardHeader(title = "UFC Dashboard"),
dashboardSidebar(
sidebarMenu(
menuItem("Weight Class",
tabName = "weight_class_tab",
icon = icon("dashboard")),
menuItem("Head to Head",
tabName = "head_tab",
icon = icon("dashboard"))
)
),
dashboardBody(
tabItems(
tabItem(tabName = "weight_class_tab",
box(plotOutput("elo_timeseries")),
box(plotOutput("elo_dist")),
box(tableOutput("top_5_table")),
box(uiOutput("weight_class_selector_1")),
box(sliderInput(inputId = "v_k_1",
label = "K for ELO",
min = 1,
max = 100,
value = 20))
),
tabItem(tabName = "head_tab",
fluidRow(box(uiOutput("fighter_selector")), box(uiOutput("opponent_selector"))),
fluidRow(box(valueBoxOutput("fighter_card")), box(valueBoxOutput("opponent_card"))),
box(uiOutput("weight_class_selector_2")),
box(sliderInput("v_k_2",
label = "K for ELO",
min = 1,
max = 100,
value = 20)))
)
)
)## This Font Awesome icon ('dashboard') does not exist:
## * if providing a custom `html_dependency` these `name` checks can
## be deactivated with `verify_fa = FALSE`
## This Font Awesome icon ('dashboard') does not exist:
## * if providing a custom `html_dependency` these `name` checks can
## be deactivated with `verify_fa = FALSE`
# Define server ----------------------------------------------------------------
server <- function(input, output) {
output$weight_class_selector_1 <- renderUI({
weight_class_1_df <- create_elo_data(input$v_k_1)
selectInput(inputId = "v_weight_class_1",
label = "Weight Class",
choices = weight_class_1_df %>%
select(weight_class) %>%
distinct() %>%
arrange(weight_class))
})
output$weight_class_selector_2 <- renderUI({
weight_class_2_df <- create_elo_data(input$v_k_2)
selectInput(inputId = "v_weight_class_2",
label = "Weight Class",
choices = weight_class_2_df %>%
select(weight_class) %>%
distinct() %>%
arrange(weight_class))
})
output$fighter_selector <- renderUI({
fighter_selector_df <- create_elo_data(input$v_k_2) %>%
filter(weight_class == input$v_weight_class_2) %>%
select(fighter) %>%
distinct() %>%
arrange(fighter)
selectInput(inputId = "v_fighter",
label = "Fighter",
choices = fighter_selector_df)
})
output$opponent_selector <- renderUI({
opponent_selector_df <- create_elo_data(input$v_k_2) %>%
filter(weight_class == input$v_weight_class_2) %>%
filter(fighter != input$v_fighter) %>%
select(fighter) %>%
distinct() %>%
arrange(fighter)
selectInput(inputId = "v_opponent",
label = "Opponent",
choices = opponent_selector_df)
})
output$top_5_table <- renderTable({
table_df <- create_elo_data(input$v_k_1)
table_df %>%
filter(weight_class == input$v_weight_class_1) %>%
group_by(fighter) %>%
arrange(desc(elo)) %>%
slice(1) %>%
ungroup() %>%
top_n(elo, n = 5) %>%
arrange(desc(elo)) %>%
select(fighter, elo) %>%
mutate(rank = row_number())
})
output$elo_timeseries <- renderPlot({
elo_timeseries_df <- create_elo_data(input$v_k_1) %>%
filter(weight_class == input$v_weight_class_1)
top_5_fighters <- elo_timeseries_df %>%
group_by(fighter) %>%
arrange(desc(elo)) %>%
slice(1) %>%
ungroup() %>%
top_n(elo, n = 5) %>%
select(fighter)
ggplot(data = elo_timeseries_df, aes(x = date, y = elo)) +
geom_point() +
geom_point(data = elo_timeseries_df %>% filter(fighter %in% top_5_fighters$fighter),
aes(x = date, y = elo, color = fighter)) +
theme(legend.position = "top")
})
output$elo_dist <- renderPlot({
elo_dist <- create_elo_data(input$v_k_1) %>%
filter(weight_class == input$v_weight_class_1)
ggplot(data = elo_dist, aes(x = elo)) + geom_histogram()
})
output$fighter_card <- renderValueBox({
elo <- elo.run(winner ~ fighter + opponent,
k = input$v_k_2,
data = elo_df)
fighter_prob <- round(100*predict(elo, data.frame(fighter = input$v_fighter, opponent = input$v_opponent)),0)
valueBox(
value = paste(fighter_prob, "%", sep = ""),
subtitle = paste(input$v_fighter, " Probability", sep = ""),
color = "blue",
icon = icon("hand-rock")
)
})
output$opponent_card <- renderValueBox({
elo <- elo.run(winner ~ fighter + opponent,
k = input$v_k_2,
data = elo_df)
opponent_prob <- round(100*predict(elo, data.frame(fighter = input$v_opponent, opponent = input$v_fighter)),0)
valueBox(
value = paste(opponent_prob, "%", sep = ""),
subtitle = paste(input$v_opponent, " Probability", sep = ""),
color = "red",
icon = icon("hand-rock")
)
})
}
# Create the Shiny app object --------------------------------------------------
shinyApp(ui = ui, server = server)##
## Listening on http://127.0.0.1:8484
## Warning: Error in filter: Problem while computing `..1 = weight_class == input$v_weight_class_1`.
## ✖ Input `..1` must be of size 10288 or 1, not size 0.
## Warning: Error in filter: Problem while computing `..1 = weight_class == input$v_weight_class_1`.
## ✖ Input `..1` must be of size 10288 or 1, not size 0.
## Warning: Error in filter: Problem while computing `..1 = weight_class == input$v_weight_class_1`.
## ✖ Input `..1` must be of size 10288 or 1, not size 0.
## Input to asJSON(keep_vec_names=TRUE) is a named vector. In a future version of jsonlite, this option will not be supported, and named vectors will be translated into arrays instead of objects. If you want JSON object output, please use a named list instead. See ?toJSON.
## Input to asJSON(keep_vec_names=TRUE) is a named vector. In a future version of jsonlite, this option will not be supported, and named vectors will be translated into arrays instead of objects. If you want JSON object output, please use a named list instead. See ?toJSON.
## Input to asJSON(keep_vec_names=TRUE) is a named vector. In a future version of jsonlite, this option will not be supported, and named vectors will be translated into arrays instead of objects. If you want JSON object output, please use a named list instead. See ?toJSON.
GitHub Link : https://github.com/aaron-chen-angus/S3729C-Lesson-Files/blob/main/S3729Cdatasciapp.R
You can run the source code below in your R Studio Cloud workspace.
# Load packages ----------------------------------------------------------------
library(shiny)
library(shinydashboard)
library(nortest)
library(mvnormtest)
library(MASS)##
## Attaching package: 'MASS'
## The following object is masked from 'package:dplyr':
##
## select
## The following object is masked from 'package:plotly':
##
## select
##
## Attaching package: 'psych'
## The following objects are masked from 'package:ggplot2':
##
## %+%, alpha
## Registered S3 method overwritten by 'quantmod':
## method from
## as.zoo.data.frame zoo
library(TTR)
# library(forecast) for forecasting time series data
# PREAMBLE begins
# READ (FOR REPORTS) https://shiny.rstudio.com/articles/generating-reports.html
# PREAMBLE ends
# Define UI --------------------------------------------------------------------
ui <- fluidPage(theme = shinytheme("sandstone"),
# tags$head(tags$style(HTML("
# .selectize-input, .selectize-dropdown {
# font-size: 75%;
# }
# "))),
navbarPage(title = "S3729C Data Science Application",
tabPanel("DataSets",
sidebarLayout(
sidebarPanel(
fileInput("file1", "Choose CSV File", accept=c('text/csv', 'text/comma-separated-values', 'text/plain', '.csv')),
radioButtons("indata", "Choice:", choices = c("Full", "Columns")),
selectInput("cols", "Choose the variable", choices = "", selected = " ", multiple = TRUE),
downloadButton('downloaddatset', "Download"),
hr(),
radioButtons("trans1", "Transformation:", choices = c("Not-Required", "log", "inverselog", "exponential", "lognormal", "standardize")),
hr(),
radioButtons("trans2", "Transformation:", choices = c("Trignometric", "Mathematical")),
textInput("trigno", "Write Trig. Function"),
textInput("mathtrans", "Math Trans.", placeholder = "Fourier or Laplace"),
hr()
),
mainPanel(tableOutput("tab1"))
)
),
navbarMenu("Descriptive Data Analysis",
tabPanel("Summary Statistics",
sidebarLayout(
sidebarPanel(
selectInput("cols1", "Choose Variable:", choices = "", selected = " ", multiple = TRUE)
),
mainPanel(
fluidRow(
h3("Summary Statistics"),
div(
verbatimTextOutput("summar")
)
)
)
)
),
tabPanel("Frequency Tables",
sidebarLayout(
sidebarPanel(
selectInput("cols2", "Choose Variable 1:", choices = "", selected = " ", multiple = TRUE),
selectInput("cols3", "Choose Variable 2:", choices = "", selected = " ", multiple = TRUE)
),
mainPanel(
fluidRow(
h3("Frequency Tables"),
div(
verbatimTextOutput("freq_tables")
)
)
)
)
),
tabPanel("Cross Tabulation",
sidebarLayout(
sidebarPanel(
selectInput("cols4", "Choose Variable 1:", choices = "", selected = " ", multiple = TRUE),
selectInput("cols5", "Choose Variable 2:", choices = "", selected = " ", multiple = TRUE),
hr(),
helpText("For details visit:"),
a(href="https://en.wikipedia.org/wiki/Chi-squared_test", "Karl Pearson Chisquare Test"),
hr()
),
mainPanel(
fluidRow(
h3("Chisquare Test"),
verbatimTextOutput("chi_t")
)
)
)
),
tabPanel("Plots",
sidebarLayout(
sidebarPanel(
radioButtons("plotoption", "Choose the Option:", choices = c("Histogram", "BarPlot", "Scatter", "Pie" )),
selectInput("cols6", "Choose Variable 1:", choices = "", selected = " ", multiple = TRUE),
textInput("xaxisname", "Write X Axis Name"),
textInput("yaxisname", "Write Y Axis Name"),
textInput("title", "Write Title For the Graph")
),
mainPanel(
h3("Plots"),
fluidRow(
plotOutput("plot")
)
)
)
)
),
navbarMenu("Predictive Data Analysis",
tabPanel("Statistical Tests",
sidebarLayout(
sidebarPanel(
selectInput("cols7", "Choose Variable 1:", choices = "", selected = " ", multiple = TRUE),
selectInput("cols8", "Choose Variable 2:", choices = "", selected = " ", multiple = TRUE),
radioButtons("normaltest", "Select Method:", choices = c("A-D-Test", "Shapiro", "KS-Test", "MV-Shapiro")),
hr(),
helpText("For more details visit:"),
a(href="https://en.wikipedia.org/wiki/Anderson%E2%80%93Darling_test", "Anderson-Darling test"), br(),
a(href="https://en.wikipedia.org/wiki/Shapiro%E2%80%93Wilk_test", "Shapiro-Wilk test"), br(),
a(href="https://en.wikipedia.org/wiki/Kolmogorov%E2%80%93Smirnov_test", "Kolmogorov-Smirnov test"), br(),
hr()
),
mainPanel(
h3("Statistical Tests"),
fluidRow(
div(
plotOutput("qqp")
),
div(
verbatimTextOutput("normtest")
)
)
)
)
),
tabPanel("Correlation",
sidebarLayout(
sidebarPanel(
selectInput("cols9", "Choose Variable:", choices = "", selected = " ", multiple = TRUE),
selectInput("cols10", "Choose Variable:", choices = "", selected = " ", multiple = TRUE),
radioButtons("cormethod", "Select Method:", choices = c("KarlPearson", "Spearman", "Kendals")),
hr(),
helpText("For Details Visit:"),
a(href="https://en.wikipedia.org/wiki/Spearman%27s_rank_correlation_coefficient", "Karl Pearson Correlation Test"),
hr()
),
mainPanel(
h3("Correlation"),
verbatimTextOutput("cor_t")
)
)
),
tabPanel("Regression & ANOVA",
sidebarLayout(
sidebarPanel(
selectInput("cols11", "Choose Variable:", choices = "", selected = " ", multiple = TRUE),
selectInput("cols12", "Choose Variable:", choices = "", selected = " ", multiple = TRUE),
radioButtons("regmethod", "Select Method:", choices = c("Fit", "Summary", "ANOVA")),
hr(),
helpText("For more information please visit"),
a(href="https://en.wikipedia.org/wiki/Simple_linear_regression", "Simple Linear Regression"),
hr()
),
mainPanel(
h3("Regression & ANOVA"),
fluidRow(
div(
verbatimTextOutput("regout")
),
div(
plotOutput("regplot")
)
)
)
)
),
tabPanel("MANOVA",
sidebarLayout(
sidebarPanel(
selectInput("cols13", "Choose Variable:", choices = "", selected = " ", multiple = TRUE),
selectInput("cols14", "Choose Variable:", choices = "", selected = " ", multiple = TRUE),
radioButtons("manmethod", "Choose Method:", choices = c("Fit", "Summary")),
hr(),
helpText("For more information please visit"),
a(href="https://en.wikipedia.org/wiki/Multivariate_analysis_of_variance", "MANOVA"),
hr(),
helpText("Right now MANOVA supports only two dependent variables"),
hr()
),
mainPanel(
h3("MANOVA"),
fluidRow(
div(
verbatimTextOutput("manovaout")
),
div(
plotOutput("manovaplot")
)
)
)
)
),
tabPanel("Forecasting",
# http://r-statistics.co/Time-Series-Analysis-With-R.html
sidebarLayout(
sidebarPanel(
selectInput("forcvar", "Select Variables:", choices = "", selected = "", multiple = TRUE),
radioButtons("forctasks", "Select Task:", choices = c("Description", "Convert", "Make-Stationary", "Decompose", "De-trend", "De-Seasonalize", "ACF", "PACF", "Predict")),
# textInput("fre", "Frequency:"),
numericInput("forclag", "Lag:", 1),
numericInput("forcdiff", "Diff:", 1),
fileInput("preddata", "Upload New Data for Prediction:", accept=c('text/csv', 'text/comma-separated-values', 'text/plain', '.csv')),
textInput("additvsmult", "Type", placeholder = "write 'additive' or 'mult'"),
radioButtons("forcanal", "Choose Method:", choices = c("Moving-Averages", "Exponential(HW)")),
radioButtons("forcplottype", "Select Plot:", choices = c("No-Plot", "TS", "ACF", "PACF")),
radioButtons("forctests", "Tests:", choices = c("No-Tests", "ADF", "KPSS"))
),
mainPanel(
h3("Forecating"),
fluidRow(
div(
verbatimTextOutput("tsconvert")
),
div(
verbatimTextOutput("forcoutput")
),
div(
plotOutput("forcplot")
)
)
)
)
)
),
navbarMenu("Exploratory Data Analysis",
tabPanel("Discriminant Analysis",
sidebarLayout(
sidebarPanel(
selectInput('dafactvar', "Choose the Factor:", choices = "", selected = ""),
selectInput('daNumvar1', "Choose the Vector1:", choices = "", selected = ""),
selectInput('daNumvar2', "Choose the Vector2:", choices = "", selected = ""),
selectInput('daNumtvar3', "Choose the Vector3:", choices = "", selected = ""),
hr(),
helpText("Supports only 3 vectors (Vector: variable at right hand side of the equation). Implements only LDA at presents. For details visit:"),
a(href="https://en.wikipedia.org/wiki/Linear_discriminant_analysis", "Discriminant Analysis"),
hr()
),
mainPanel(
h3("Discriminant Analysis"),
fluidRow(
div(
verbatimTextOutput("daoutput")
),
div(
plotOutput("daplot")
)
)
)
)
),
tabPanel("Reliability Analysis",
sidebarLayout(
sidebarPanel(
selectInput("relalpha", "Choose the variables:", choices = "", selected = "", multiple = TRUE),
hr(),
helpText("For more details visit:"),
a(href="https://en.wikipedia.org/wiki/Cronbach%27s_alpha", "Cronbach's alpha"),
hr()
),
mainPanel(
h3("Reliability Analysis"),
div(
verbatimTextOutput("reloutput")
)
)
)
),
tabPanel("Factor Analysis",
sidebarLayout(
sidebarPanel(
selectInput("fadataset", "Choose the Variables:", choices = "", selected = "", multiple = TRUE),
textInput("nf", "Mention No. of Factors", value = "2", width = NULL, placeholder = "Write here number of factors"),
hr(),
helpText("For details visit:"),
a(href="https://en.wikipedia.org/wiki/Factor_analysis", "Factor Analysis"),
hr()
),
mainPanel(
h3("Factor Analysis"),
div(
verbatimTextOutput("faoutput")
),
div(
plotOutput("faplot")
)
)
)
),
tabPanel("Cluster Analysis",
sidebarLayout(
sidebarPanel(
selectInput("cavars", "Choose Variables:", choices = "", selected = "", multiple = TRUE),
textInput("nc", "Number of Clusters:", value = "2", placeholder = "Choose No. Clusters"),
radioButtons("showcl", "Show Individuals by Clusters:", choices = c("ShowClus", "NoClus")),
hr(),
helpText("For more details visit:"),
a(href="https://en.wikipedia.org/wiki/Cluster_analysis", "Cluster analysis"),
hr()
),
mainPanel(
h3("Cluster Analysis"),
div(
verbatimTextOutput("caoutput")
),
div(
plotOutput("caplot")
)
)
)
)
),
# tabPanel("REPORTS",
# sidebarLayout(
# sidebarPanel("Reports"),
# mainPanel(tableOutput("pdfview"))
# )
# ),
tabPanel("About",
sidebarLayout(
sidebarPanel(
"Information about this App"
),
mainPanel(htmlOutput("text1"))
)
)
)
)
# Define server ----------------------------------------------------------------
server <- function(input, output, session) {
# for DATASET TAB
data_input <- reactive({
infile <- input$file1
req(infile)
data.frame(read.csv(infile$datapath))
})
observeEvent(input$file1,{
updateSelectInput(session, inputId = "cols", choices = names(data_input()))
}
)
logno <- reactive({
df <- data_input()
x <- matrix(NA, length(df[, input$cols]), length(df[, input$cols][[1]]))
for(i in 1:length(df[, input$cols])){
for(j in 1:length(df[, input$cols][[1]])){
x[i, j] <- dlnorm(df[, input$cols][[i]][j])
}
}
return(t(x))
})
standout <- reactive({
df <- data_input()
x <- matrix(NA, length(df[, input$cols]), length(df[, input$cols][[1]]))
if(!is.list(df[, input$cols])){
df[, input$cols] <- list(df[, input$cols])
}
for(i in 1:length(df[, input$cols])){
for(j in 1:length(df[, input$cols][[1]])){
x[i, j] <- df[, input$cols][[i]][j]-mean(df[, input$cols][[i]])/sd(df[, input$cols][[i]])
}
}
return(t(x))
})
output$tab1 <- renderTable(
{
df <- data_input()
if (input$indata == "Full"){
print(df)
} else if(input$trans1 == "Not-Required"){
data <- df[, input$cols]
print(data)
} else if(input$trans1 == "log"){
data <- log(df[input$cols])
print(data)
} else if(input$trans1 == "inverselog"){
data <- 1/log(df[input$cols])
print(data)
} else if(input$trans1 == "exponential"){
data <- exp(df[input$cols])
print(data)
} else if(input$trans1 == "lognormal"){
logno()
} else if(input$trans1 == "standardize"){
standout()
}
}
)
output$downloaddatset <- downloadHandler(
filename <- function(){
paste("data-", Sys.Date(), ".csv", sep = "")
},
content <- function(file){
df <- data_input()
write.csv(df[, input$cols], file, row.names = TRUE)
}
)
observeEvent(input$file1, {
updateSelectInput(session, inputId = "cols1", choices = names(data_input()))
}
)
summ <- reactive({
var1 <- data_input()[,input$cols1]
su <- summary(var1)
return(su)
})
output$summar <- renderPrint({
summ()
})
# frequency tab
observeEvent(input$file1, {
updateSelectInput(session, inputId = "cols2", choices = names(data_input()))
updateSelectInput(session, inputId = "cols3", choices = names(data_input()))
}
)
freq <- reactive({
var1 <- data_input()[,input$cols2]
var2 <- data_input()[,input$cols3]
fre <- table(var1, var2)
return(fre)
})
output$freq_tables <- renderPrint({
freq()
})
# Cross tabulation
observeEvent(input$file1, {
updateSelectInput(session, inputId = "cols4", choices = names(data_input()))
updateSelectInput(session, inputId = "cols5", choices = names(data_input()))
}
)
cross <- reactive({
var1 <- data_input()[,input$cols4]
var2 <- data_input()[,input$cols5]
cro <- chisq.test(var1, var2)
return(cro)
})
output$chi_t <- renderPrint({
cross()
})
# Plots
observeEvent(input$file1, {
updateSelectInput(session, inputId = "cols6", choices = names(data_input()))
}
)
output$plot <- renderPlot({
df <- data_input()
if(input$plotoption == "Histogram"){
hist(df[, input$cols6], freq = FALSE, xlab = input$xaxisname, ylab = input$yaxisname, main = input$title); lines(density(df[, input$cols6]), col = "red", lwd = 1.5)
} else if(input$plotoption == "BarPlot"){
barplot(df[, input$cols6], xlab = input$xaxisname, ylab = input$yaxisname, main = input$title)
} else if(input$plotoption == "Scatter"){
scatter.smooth(df[, input$cols6], xlab = input$xaxisname, ylab = input$yaxisname, main = input$title)
} else {
pie(table(df[, input$cols6]))
}
})
# Statistical Tests
observeEvent(input$file1, {
updateSelectInput(session, inputId = "cols7", choices = names(data_input()))
updateSelectInput(session, inputId = "cols8", choices = names(data_input()))
}
)
output$qqp <- renderPlot({
df <- data_input()
qqnorm(df[, input$cols7]);qqline(df[, input$cols7])
})
adt <- reactive({
df <- data_input()
var <- df[, input$cols7]
ad <- ad.test(var)
return(ad)
})
sht <- reactive({
df <- data_input()
var <- df[, input$cols7]
sh <- shapiro.test(var)
return(sh)
})
kst <- reactive({
df <- data_input()
var1 <- df[, input$cols7]
var2 <- df[, input$cols8]
ks <- ks.test(var1, var2)
return(ks)
})
mvst <- reactive({
df <- data_input()
var1 <- df[, input$cols7]
var2 <- df[, input$cols8]
return(mshapiro.test(t(as.data.frame(var1, var2))))
})
output$normtest <- renderPrint({
if(input$normaltest == "A-D-Test"){
print(adt())
} else if(input$normaltest == "Shapiro"){
print(sht())
} else if(input$normaltest == "KS-Test"){
print(kst())
} else if(input$normaltest == "MV-Shapiro"){
print(mvst())
}
}
)
# correlation & regression
observeEvent(input$file1, {
updateSelectInput(session, inputId = "cols9", choices = names(data_input()))
updateSelectInput(session, inputId = "cols10", choices = names(data_input()))
}
)
cortest <- reactive({
var1 <- data_input()[,input$cols9]
var2 <- data_input()[,input$cols10]
if (input$cormethod == "KarlPearson"){
return(cor.test(var1, var2, method = "pearson"))
} else if(input$cormethod == "Spearman"){
return(cor.test(var1, var2, method="spearman"))
} else {
return(cor.test(var1, var2, method="kendall"))
}
}
)
output$cor_t <- renderPrint({
cortest()
})
# Regression
observeEvent(input$file1, {
updateSelectInput(session, inputId = "cols11", choices = names(data_input()))
updateSelectInput(session, inputId = "cols12", choices = names(data_input()))
}
)
reganal <- reactive({
df <- data_input()
var1 <- df[, input$cols11]
var2 <- df[, input$cols12]
rego <- lm(var1 ~ var2, data = df)
return(list(fit = rego, fitsum = summary(rego), anov = anova(rego)))
})
output$regout <- renderPrint({
if (input$regmethod == "Fit"){
reganal()$fit
} else if(input$regmethod == "Summary"){
reganal()$fitsum
} else if(input$regmethod == "ANOVA"){
reganal()$anov
}
})
output$regplot <- renderPlot({
df <- data_input()
var1 <- df[, input$cols11]
var2 <- df[, input$cols12]
plot(var1, var2); abline(lm(var1 ~ var2, data = df), col = "red", lwd=2)
})
# MANOVA
observeEvent(input$file1, {
updateSelectInput(session, inputId = "cols13", choices = names(data_input()))
updateSelectInput(session, inputId = "cols14", choices = names(data_input()))
}
)
manovaform <- reactive({
df <- data_input()
#formula <- as.formula(paste(cbind(df[, input$cols13]), '~', df[, input$cols14]))
manform <- as.formula(paste("cbind(unlist(rbind(df[, input$cols13]))[1:length(df[, input$cols14])], unlist(rbind(df[, input$cols13]))[length(df[, input$cols14])+1:length(df[, input$cols14])*2])", "~", "df[, input$cols14]"))
return(manform)
})
manovaanal <- reactive({
df <- data_input()
manout <- manova(manovaform(), data = df)
return(manout)
})
output$manovaout <- renderPrint({
if(input$manmethod=="Fit"){
manovaanal()
} else if(input$manmethod == "Summary"){
summary(manovaanal())
}
})
output$manovaplot <- renderPlot({
df <- data_input()
var1 <- df[, input$cols13]
var2 <- df[, input$cols14]
plot(data.frame(var1, var2))
})
# Forecasting
observeEvent(input$file1, {
updateSelectInput(session, inputId = "forcvar", choices = names(data_input()))
}
)
# tsconver <- reactive({
# df <- data_input()
# # out <- ts(df[, input$forcvar], frequency = input$freq, start = c(input$startyr, input$startmonth))
# out <- ts(df[, input$forcvar]) # , freq = input$freq, start = c(input$startyr, input$startmonth))
# return(out)
# })
# output$tsconvert <- renderPrint({
# tsconver()
# })
tstasks <- reactive({
df <- data_input()
if (input$forctasks == "Convert"){
out <- ts(df[, input$forcvar]) # , freq = input$freq, start = c(input$startyr, input$startmonth))
return(out)
} else if(input$forctasks == "Make-Stationary"){
dif <- diff(df[, input$forcvar], input$forclag, input$forcdiff)
return(dif)
} else if (input$forctasks == "Decompose"){
out <- decompose(ts(df[, input$forcvar], frequency = 4, start = 1), type = input$additvsmult)
return(out)
} else if (input$forctasks == "De-trend"){
dtmodel <- lm(df[, input$forcvar] ~ c(1:length(df[, input$forcvar])))
out <- resid(dtmodel)
return(out)
} else if(input$forctasks == "De-Seasonalize"){
ddc <- decompose(ts(df[, input$forcvar], frequency = 4, start = 1), type = input$additvsmult)
out <- df[, input$forcvar]-unlist(ddc["seasonal"])
return(as.data.frame(out)$out)
} else if(input$forctests == "ADF"){
out <- adf.test(ts(df[, input$forcvar], frequency = 4, start = 1))
return(out)
} else if(input$forctests == "KPSS"){
out <- kpss.test(ts(df[, input$forcvar], frequency = 4, start = 1))
return(out)
} else if(input$forctasks == "ACF"){
out <- acf(ts(df[, input$forcvar]))
return(out)
} else if(input$forctasks == "PACF"){
out <- pacf(ts(df[, input$forcvar]))
return(out)
} else if(input$forcanal == "Moving-Averages"){
out <- SMA(ts(df[, input$forcvar]))
return(out)
} else if(input$forcanal == "Exponential(HW)"){
out <- HoltWinters(ts(df[, input$forcvar], frequency = 4, start = 1))
return(out)
}
})
desctext <- reactive({
cat("Welcome to Forecasting; Following is the very little documentation on methods", "\n", "Convert: Converts given data variable into a time series data.",
"\n", "Make-Stationary: Makes time series into stationary; requires inputs viz. Lag, Diff.",
"\n", "Decompose: Decomposes data set into three components viz. trend, seasonal, random; methods - 'additive' or 'mult'.",
"\n", "Detrend: Eleminates Trend component.",
"\n", "Deseasonlize: Eleminates Seasonal component.",
"\n", "ACF: Autocorrelation Function.",
"\n", "PACF: Partial Autocorrelation Function.",
"\n", "Predict: Not implemented Yet.",
"\n", "Moving Averages: Computes moving average default number is 1.",
"\n", "Exponential(HW): Computes Holt-Winter estimates.")
})
output$forcoutput <- renderPrint({
if (input$forctasks == "Description"){
desctext()
} else if(input$forctasks == "Convert"){
tstasks()
} else if(input$forctasks == "De-trend"){
list(head(tstasks()), "Only first 6 records are displayed")
} else if(input$forctasks == "Make-Stationary"){
return(tstasks())
} else if(input$forctasks == "Decompose"){
tstasks()
} else if(input$forctasks == "De-Seasonalize"){
print(list(info = "Only First Few Records are Printed", head(tstasks())))
} else if(input$forctests == "ADF"){
tstasks()
} else if(input$forctests == "KPSS"){
tstasks()
} else if(input$forctasks == "ACF"){
tstasks()$acf
} else if(input$forctasks == "PACF"){
tstasks()$acf
} else if(input$forcanal == "Moving-Averages"){
tstasks()
} else if(input$forcanal == "Exponential(HW)"){
tstasks()
}
}
)
output$forcplot <- renderPlot({
# df <- data_input()
if (input$forctasks == "De-trend" & input$forcplottype == "TS"){
plot(tstasks(), type = "b", col = "red")
} else if (input$forctasks == "Make-Stationary" & input$forcplottype == "TS"){
plot(tstasks(), type = "b", col = "red", lwd = 1.75)
} else if (input$forctasks == "Decompose" & input$forcplottype == "TS"){
plot(tstasks(), type = "b", col = "red", lwd = 1.75)
} else if(input$forctasks == "De-Seasonalize" & input$forcplottype == "TS"){
plot(tstasks(), type ="b", col = "red", lwd = 1.75)
} else if (input$forctasks == "Convert" & input$forcplottype == "TS"){
plot(tstasks(), type = "b", col = "red", lwd = 1.75)
} else if(input$forctasks == "ACF" & input$forcplottype == "ACF"){
plot(tstasks())
} else if(input$forctasks == "PACF" & input$forcplottype == "PACF"){
plot(tstasks())
} else if(input$forcanal == "Moving-Averages" & input$forcplottype == "TS"){
plot(tstasks())
}
})
# Exploratory
# Disctiminant Analysi s
observeEvent(input$file1, {
updateSelectInput(session, inputId = "dafactvar", choices = names(data_input()))
updateSelectInput(session, inputId = "daNumvar1", choices = names(data_input()))
updateSelectInput(session, inputId = "daNumvar2", choices = names(data_input()))
updateSelectInput(session, inputId = "daNumtvar3", choices = names(data_input()))
}
)
daout <- reactive({
df <- data_input()
var1 <- df[, input$dafactvar]
var2 <- df[, input$daNumvar1]
var3 <- df[, input$daNumvar2]
var4 <- df[, input$daNumtvar3]
daformula <- as.formula(paste("var1", "~", "var2", "+", "var3", "+", "var4"))
fit <- lda(daformula, data = df)
return(fit)
})
output$daoutput <- renderPrint({
daout()
})
output$daplot <- renderPlot({
plot(daout(), dimen=1, type="both")
})
# Reliability analysis
observeEvent(input$file1, {
updateSelectInput(session, inputId = "relalpha", choices = names(data_input()))
}
)
relout <- reactive({
df <- data_input()
out <- alpha(df[, input$relalpha])
return(out)
})
output$reloutput <- renderPrint({
relout()
})
# FActor analysis
observeEvent(input$file1, {
updateSelectInput(session, inputId = "fadataset", choices = names(data_input()))
}
)
faout <- reactive({
df <- data_input()
# out <- factanal(matrix(unlist(list(df[, input$fadataset])), dim(df)[1], length(input$fadataset)), input$nf)
out <- fa(df[, input$fadataset], input$nf)
return(out)
})
output$faoutput <- renderPrint({
faout()
})
output$faplot <- renderPlot({
plot(faout())
})
# Cluster analysis
observeEvent(input$file1, {
updateSelectInput(session, inputId = "cavars", choices = names(data_input()))
}
)
caout <- reactive({
df <- data_input()
out <- kmeans(df[,input$cavars], input$nc)
return(out)
})
output$caoutput <- renderPrint({
df <- data_input()
if(input$showcl == "NoClus"){
caout()
} else if(input$showcl == "ShowClus"){
out <- cbind(1:dim(df)[1], caout()$cluster)
colnames(out) <- c("individuals", "Cluster")
print(out)
}
})
output$caplot <- renderPlot({
df <- data_input()
clusplot(df, caout()$cluster, color = TRUE, shade = TRUE, labels = 2, lines = 0)
})
# About this App
output$text1 <- renderText({
str1 <- paste("Created using R Shiny")
str2 <- paste("for S3729C Lesson 14")
str3 <- paste("visit https://shiny.rstudio.com for more information")
HTML(paste(str1, str2, str3, sep = '<br/>'))
})
}
# Create the Shiny app object --------------------------------------------------
shinyApp(ui, server)##
## Listening on http://127.0.0.1:7652