library(FinancialMath)

# kapital pozostajacy do splacenia
kapital <- 45058.08

# liczba pozostalych rat
lba_pozostalych_rat <- 185

# oprocentowanie
oprocentowanie <- c(2.35, 2.45)

# liczba dni w jakich obowiazywalo oprocentowanie
# 20.01.2021  ZMIANA WYSOKOSCI ODSETEK
dni_oprocentowania <- c(20, 11)

##########################################
#
#               rata #175
#
##########################################

oprocentowanie <- oprocentowanie / 100
rata <- amort.period(Loan = kapital, n = lba_pozostalych_rat, i = oprocentowanie[2], ic = 12, pf = 12)
rata <- round(rata[2], digits = 2)

# obliczanie raty kapitalowej przy zalozeniu ze przez caly okres obowiazuje oprocentowanie docelowe
rata_odsetkowa_doc <- round(kapital * sum(dni_oprocentowania) / 365 * oprocentowanie[2], digits = 2)
rata_kapitalowa <- rata - rata_odsetkowa_doc

# oblicanie faktycznej raty odsetkowej
rata_odsetkowa <- kapital * dni_oprocentowania / 365 * oprocentowanie
rata_odsetkowa <- round(sum(rata_odsetkowa), digits = 2)

cat("rata_kapitalowa[175] = ", rata_kapitalowa, "\n")
cat("rata_odsetkowa[175] = ", rata_odsetkowa, "\n")
cat("rata[175] = ", rata_kapitalowa + rata_odsetkowa, "\n")
cat("rata[176+] = ", rata, "\n")


# ----------------------------------------
#  App Title: Benford's Law and Sequences
#     Author: Jimmy Doi
# ----------------------------------------
library(shinyIncubator)

shinyUI(navbarPage("Benford's Law: Sequences",

###################################################################################################
## tabPanel: Additive Sequence                                                                   ##
###################################################################################################
tabPanel("(1) Additive Sequence",
   fluidPage(
       tags$head(tags$link(rel = "icon", type = "image/x-icon", href =
       "https://webresource.its.calpoly.edu/cpwebtemplate/5.0.1/common/images_html/favicon.ico")),

       progressInit(),

       # Give the page a title
       h3("Benford's Law: Additive Sequence"),

        div("Note: Please adjust width of browser if only one column is visible.",br(),
            HTML("[Click here for another Shiny app on Benford's Law]"),
            style = "font-size: 9pt;color:teal"),br(),

       p("Consider a sequence of numbers where we fix the initial two numbers and then the
         value of each subsequent number is the sum of the previous two. We will call this an",
         tags$b("additive sequence."),
         "When the initial two numbers are both 1 then this yields the famous Fibonacci sequence.
         If you only consider the first digit of each number in an additive sequence and examine its distribution,
         is it the case that it closely follows ",
         HTML("Benford's Law?"),
         "This app generates an additive sequence, for a given length and initial sequence numbers,
         and applies a goodness of fit test of the observed frequencies of first digits to Benford's Law",
         style="font-size:11pt"),
       HTML("
"),

       # Generate a row with a sidebar
       fluidRow(

         column(4,wellPanel(

           sliderInput("seq1",
                       label = h5("First Sequence Number"),
                       min = 1, max = 9, value = 1, step=1),br(),

           sliderInput("seq2",
                       label = h5("Second Sequence Number"),
                       min = 1, max = 9, value = 1, step=1),br(),

           sliderInput("length",
                       label = h5(HTML("Length of sequence (n)")),
                       min = 150, max = 1000, value = 150, step=50),br(),

           br(), br(), br(), br(),

           div("Shiny app by",
               a(href="http://statweb.calpoly.edu/jdoi/",target="_blank",
                 "Jimmy Doi"),align="right", style = "font-size: 8pt"),

           div("Base R code by",
               a(href="http://statweb.calpoly.edu/jdoi/",target="_blank",
                 "Jimmy Doi"),align="right", style = "font-size: 8pt"),

           div("Shiny source files:",
               a(href="https://gist.github.com/calpolystat/f4475cbfe4cc77cef168",
                 target="_blank","GitHub Gist"),align="right", style = "font-size: 8pt"),

           div(a(href="http://www.statistics.calpoly.edu/shiny",target="_blank",
                 "Cal Poly Statistics Dept Shiny Series"),align="right", style = "font-size: 8pt")
         )),
         column(8,
          div(span(tags$b("First 50 numbers in the sequence (first digit in"),style="font-size:9pt"),
              span(
                span("red",style="font-size:9pt; color:red; font-weight:bold"),tags$b("):",
                conditionalPanel("input.seq1==1 & input.seq2==1",
                  span(HTML("   "),"[Fibonacci sequence]",
                  style="text-align: right;color:blue;font-size:9pt;display:inline-block"),
                  style="text-align: right;font-size:0pt;display:inline-block;"),
                conditionalPanel("input.seq1==2 & input.seq2==1",
                  span(HTML("   "),"[Lucas sequence]",
                  style="text-align: right;color:blue;font-size:9pt;display:inline-block"),
                  style="text-align: right;font-size:0pt;display:inline-block;"),style="font-size:9pt")),
              style="font-size:0pt"),
          div(
            div(span(textOutput("num.1a"),style="font-size: 9pt; color:red; font-weight:bold; display:inline-block"),
                span(textOutput("num.1b"),style="font-size: 9pt; color:black; display:inline-block"),span(HTML(" "),style="font-size:9pt"),
                style="display:inline-block"),
            div(span(textOutput("num.2a"),style="font-size: 9pt; color:red; font-weight:bold; display:inline-block"),
                span(textOutput("num.2b"),style="font-size: 9pt; color:black; display:inline-block"),span(HTML(" "),style="font-size:9pt"),
                style="display:inline-block"),
            div(span(textOutput("num.3a"),style="font-size: 9pt; color:red; font-weight:bold; display:inline-block"),
                span(textOutput("num.3b"),style="font-size: 9pt; color:black; display:inline-block"),span(HTML(" "),style="font-size:9pt"),
                style="display:inline-block"),
            div(span(textOutput("num.4a"),style="font-size: 9pt; color:red; font-weight:bold; display:inline-block"),
                span(textOutput("num.4b"),style="font-size: 9pt; color:black; display:inline-block"),span(HTML(" "),style="font-size:9pt"),
                style="display:inline-block"),
            div(span(textOutput("num.5a"),style="font-size: 9pt; color:red; font-weight:bold; display:inline-block"),
                span(textOutput("num.5b"),style="font-size: 9pt; color:black; display:inline-block"),span(HTML(" "),style="font-size:9pt"),
                style="display:inline-block"),
            div(span(textOutput("num.6a"),style="font-size: 9pt; color:red; font-weight:bold; display:inline-block"),
                span(textOutput("num.6b"),style="font-size: 9pt; color:black; display:inline-block"),span(HTML(" "),style="font-size:9pt"),
                style="display:inline-block"),
            div(span(textOutput("num.7a"),style="font-size: 9pt; color:red; font-weight:bold; display:inline-block"),
                span(textOutput("num.7b"),style="font-size: 9pt; color:black; display:inline-block"),span(HTML(" "),style="font-size:9pt"),
                style="display:inline-block"),
            div(span(textOutput("num.8a"),style="font-size: 9pt; color:red; font-weight:bold; display:inline-block"),
                span(textOutput("num.8b"),style="font-size: 9pt; color:black; display:inline-block"),span(HTML(" "),style="font-size:9pt"),
                style="display:inline-block"),
            div(span(textOutput("num.9a"),style="font-size: 9pt; color:red; font-weight:bold; display:inline-block"),
                span(textOutput("num.9b"),style="font-size: 9pt; color:black; display:inline-block"),span(HTML(" "),style="font-size:9pt"),
                style="display:inline-block"),
            div(span(textOutput("num.10a"),style="font-size: 9pt; color:red; font-weight:bold; display:inline-block"),
                span(textOutput("num.10b"),style="font-size: 9pt; color:black; display:inline-block"),span(HTML(" "),style="font-size:9pt"),
                style="display:inline-block"),
            div(span(textOutput("num.11a"),style="font-size: 9pt; color:red; font-weight:bold; display:inline-block"),
                span(textOutput("num.11b"),style="font-size: 9pt; color:black; display:inline-block"),span(HTML(" "),style="font-size:9pt"),
                style="display:inline-block"),
            div(span(textOutput("num.12a"),style="font-size: 9pt; color:red; font-weight:bold; display:inline-block"),
                span(textOutput("num.12b"),style="font-size: 9pt; color:black; display:inline-block"),span(HTML(" "),style="font-size:9pt"),
                style="display:inline-block"),
            div(span(textOutput("num.13a"),style="font-size: 9pt; color:red; font-weight:bold; display:inline-block"),
                span(textOutput("num.13b"),style="font-size: 9pt; color:black; display:inline-block"),span(HTML(" "),style="font-size:9pt"),
                style="display:inline-block"),
            div(span(textOutput("num.14a"),style="font-size: 9pt; color:red; font-weight:bold; display:inline-block"),
                span(textOutput("num.14b"),style="font-size: 9pt; color:black; display:inline-block"),span(HTML(" "),style="font-size:9pt"),
                style="display:inline-block"),
            div(span(textOutput("num.15a"),style="font-size: 9pt; color:red; font-weight:bold; display:inline-block"),
                span(textOutput("num.15b"),style="font-size: 9pt; color:black; display:inline-block"),span(HTML(" "),style="font-size:9pt"),
                style="display:inline-block"),
            div(span(textOutput("num.16a"),style="font-size: 9pt; color:red; font-weight:bold; display:inline-block"),
                span(textOutput("num.16b"),style="font-size: 9pt; color:black; display:inline-block"),span(HTML(" "),style="font-size:9pt"),
                style="display:inline-block"),
            div(span(textOutput("num.17a"),style="font-size: 9pt; color:red; font-weight:bold; display:inline-block"),
                span(textOutput("num.17b"),style="font-size: 9pt; color:black; display:inline-block"),span(HTML(" "),style="font-size:9pt"),
                style="display:inline-block"),
            div(span(textOutput("num.18a"),style="font-size: 9pt; color:red; font-weight:bold; display:inline-block"),
                span(textOutput("num.18b"),style="font-size: 9pt; color:black; display:inline-block"),span(HTML(" "),style="font-size:9pt"),
                style="display:inline-block"),
            div(span(textOutput("num.19a"),style="font-size: 9pt; color:red; font-weight:bold; display:inline-block"),
                span(textOutput("num.19b"),style="font-size: 9pt; color:black; display:inline-block"),span(HTML(" "),style="font-size:9pt"),
                style="display:inline-block"),
            div(span(textOutput("num.20a"),style="font-size: 9pt; color:red; font-weight:bold; display:inline-block"),
                span(textOutput("num.20b"),style="font-size: 9pt; color:black; display:inline-block"),span(HTML(" "),style="font-size:9pt"),
                style="display:inline-block"),
            div(span(textOutput("num.21a"),style="font-size: 9pt; color:red; font-weight:bold; display:inline-block"),
                span(textOutput("num.21b"),style="font-size: 9pt; color:black; display:inline-block"),span(HTML(" "),style="font-size:9pt"),
                style="display:inline-block"),
            div(span(textOutput("num.22a"),style="font-size: 9pt; color:red; font-weight:bold; display:inline-block"),
                span(textOutput("num.22b"),style="font-size: 9pt; color:black; display:inline-block"),span(HTML(" "),style="font-size:9pt"),
                style="display:inline-block"),
            div(span(textOutput("num.23a"),style="font-size: 9pt; color:red; font-weight:bold; display:inline-block"),
                span(textOutput("num.23b"),style="font-size: 9pt; color:black; display:inline-block"),span(HTML(" "),style="font-size:9pt"),
                style="display:inline-block"),
            div(span(textOutput("num.24a"),style="font-size: 9pt; color:red; font-weight:bold; display:inline-block"),
                span(textOutput("num.24b"),style="font-size: 9pt; color:black; display:inline-block"),span(HTML(" "),style="font-size:9pt"),
                style="display:inline-block"),
            div(span(textOutput("num.25a"),style="font-size: 9pt; color:red; font-weight:bold; display:inline-block"),
                span(textOutput("num.25b"),style="font-size: 9pt; color:black; display:inline-block"),span(HTML(" "),style="font-size:9pt"),
                style="display:inline-block"),
            div(span(textOutput("num.26a"),style="font-size: 9pt; color:red; font-weight:bold; display:inline-block"),
                span(textOutput("num.26b"),style="font-size: 9pt; color:black; display:inline-block"),span(HTML(" "),style="font-size:9pt"),
                style="display:inline-block"),
            div(span(textOutput("num.27a"),style="font-size: 9pt; color:red; font-weight:bold; display:inline-block"),
                span(textOutput("num.27b"),style="font-size: 9pt; color:black; display:inline-block"),span(HTML(" "),style="font-size:9pt"),
                style="display:inline-block"),
            div(span(textOutput("num.28a"),style="font-size: 9pt; color:red; font-weight:bold; display:inline-block"),
                span(textOutput("num.28b"),style="font-size: 9pt; color:black; display:inline-block"),span(HTML(" "),style="font-size:9pt"),
                style="display:inline-block"),
            div(span(textOutput("num.29a"),style="font-size: 9pt; color:red; font-weight:bold; display:inline-block"),
                span(textOutput("num.29b"),style="font-size: 9pt; color:black; display:inline-block"),span(HTML(" "),style="font-size:9pt"),
                style="display:inline-block"),
            div(span(textOutput("num.30a"),style="font-size: 9pt; color:red; font-weight:bold; display:inline-block"),
                span(textOutput("num.30b"),style="font-size: 9pt; color:black; display:inline-block"),span(HTML(" "),style="font-size:9pt"),
                style="display:inline-block"),
            div(span(textOutput("num.31a"),style="font-size: 9pt; color:red; font-weight:bold; display:inline-block"),
                span(textOutput("num.31b"),style="font-size: 9pt; color:black; display:inline-block"),span(HTML(" "),style="font-size:9pt"),
                style="display:inline-block"),
            div(span(textOutput("num.32a"),style="font-size: 9pt; color:red; font-weight:bold; display:inline-block"),
                span(textOutput("num.32b"),style="font-size: 9pt; color:black; display:inline-block"),span(HTML(" "),style="font-size:9pt"),
                style="display:inline-block"),
            div(span(textOutput("num.33a"),style="font-size: 9pt; color:red; font-weight:bold; display:inline-block"),
                span(textOutput("num.33b"),style="font-size: 9pt; color:black; display:inline-block"),span(HTML(" "),style="font-size:9pt"),
                style="display:inline-block"),
            div(span(textOutput("num.34a"),style="font-size: 9pt; color:red; font-weight:bold; display:inline-block"),
                span(textOutput("num.34b"),style="font-size: 9pt; color:black; display:inline-block"),span(HTML(" "),style="font-size:9pt"),
                style="display:inline-block"),
            div(span(textOutput("num.35a"),style="font-size: 9pt; color:red; font-weight:bold; display:inline-block"),
                span(textOutput("num.35b"),style="font-size: 9pt; color:black; display:inline-block"),span(HTML(" "),style="font-size:9pt"),
                style="display:inline-block"),
            div(span(textOutput("num.36a"),style="font-size: 9pt; color:red; font-weight:bold; display:inline-block"),
                span(textOutput("num.36b"),style="font-size: 9pt; color:black; display:inline-block"),span(HTML(" "),style="font-size:9pt"),
                style="display:inline-block"),
            div(span(textOutput("num.37a"),style="font-size: 9pt; color:red; font-weight:bold; display:inline-block"),
                span(textOutput("num.37b"),style="font-size: 9pt; color:black; display:inline-block"),span(HTML(" "),style="font-size:9pt"),
                style="display:inline-block"),
            div(span(textOutput("num.38a"),style="font-size: 9pt; color:red; font-weight:bold; display:inline-block"),
                span(textOutput("num.38b"),style="font-size: 9pt; color:black; display:inline-block"),span(HTML(" "),style="font-size:9pt"),
                style="display:inline-block"),
            div(span(textOutput("num.39a"),style="font-size: 9pt; color:red; font-weight:bold; display:inline-block"),
                span(textOutput("num.39b"),style="font-size: 9pt; color:black; display:inline-block"),span(HTML(" "),style="font-size:9pt"),
                style="display:inline-block"),
            div(span(textOutput("num.40a"),style="font-size: 9pt; color:red; font-weight:bold; display:inline-block"),
                span(textOutput("num.40b"),style="font-size: 9pt; color:black; display:inline-block"),span(HTML(" "),style="font-size:9pt"),
                style="display:inline-block"),
            div(span(textOutput("num.41a"),style="font-size: 9pt; color:red; font-weight:bold; display:inline-block"),
                span(textOutput("num.41b"),style="font-size: 9pt; color:black; display:inline-block"),span(HTML(" "),style="font-size:9pt"),
                style="display:inline-block"),
            div(span(textOutput("num.42a"),style="font-size: 9pt; color:red; font-weight:bold; display:inline-block"),
                span(textOutput("num.42b"),style="font-size: 9pt; color:black; display:inline-block"),span(HTML(" "),style="font-size:9pt"),
                style="display:inline-block"),
            div(span(textOutput("num.43a"),style="font-size: 9pt; color:red; font-weight:bold; display:inline-block"),
                span(textOutput("num.43b"),style="font-size: 9pt; color:black; display:inline-block"),span(HTML(" "),style="font-size:9pt"),
                style="display:inline-block"),
            div(span(textOutput("num.44a"),style="font-size: 9pt; color:red; font-weight:bold; display:inline-block"),
                span(textOutput("num.44b"),style="font-size: 9pt; color:black; display:inline-block"),span(HTML(" "),style="font-size:9pt"),
                style="display:inline-block"),
            div(span(textOutput("num.45a"),style="font-size: 9pt; color:red; font-weight:bold; display:inline-block"),
                span(textOutput("num.45b"),style="font-size: 9pt; color:black; display:inline-block"),span(HTML(" "),style="font-size:9pt"),
                style="display:inline-block"),
            div(span(textOutput("num.46a"),style="font-size: 9pt; color:red; font-weight:bold; display:inline-block"),
                span(textOutput("num.46b"),style="font-size: 9pt; color:black; display:inline-block"),span(HTML(" "),style="font-size:9pt"),
                style="display:inline-block"),
            div(span(textOutput("num.47a"),style="font-size: 9pt; color:red; font-weight:bold; display:inline-block"),
                span(textOutput("num.47b"),style="font-size: 9pt; color:black; display:inline-block"),span(HTML(" "),style="font-size:9pt"),
                style="display:inline-block"),
            div(span(textOutput("num.48a"),style="font-size: 9pt; color:red; font-weight:bold; display:inline-block"),
                span(textOutput("num.48b"),style="font-size: 9pt; color:black; display:inline-block"),span(HTML(" "),style="font-size:9pt"),
                style="display:inline-block"),
            div(span(textOutput("num.49a"),style="font-size: 9pt; color:red; font-weight:bold; display:inline-block"),
                span(textOutput("num.49b"),style="font-size: 9pt; color:black; display:inline-block"),span(HTML(" "),style="font-size:9pt"),
                style="display:inline-block"),
            div(span(textOutput("num.50a"),style="font-size: 9pt; color:red; font-weight:bold; display:inline-block"),
                span(textOutput("num.50b"),style="font-size: 9pt; color:black; display:inline-block"),span(HTML(" "),style="font-size:9pt"),
                span("",style="font-size: 9pt"),style="display:inline-block"),
            style="font-size:0;"),

          div(span("[Sequence has ",style="text-align: right;font-size:9pt;display:inline-block"),
              span(HTML(" "),style="text-align: right;font-size:9pt"),
              span(textOutput("textlength"),style="text-align: right;font-size:9pt;display:inline-block;color:teal"),
              span(HTML(" "),style="text-align: right;font-size:9pt"),
              span("numbers total]",style="text-align: right;font-size:9pt;display:inline-block"),
                                                         style="text-align: right;font-size:0pt;display:inline-block;"),

          HTML("
"),

          fluidRow(
            column(4,
                   p(tags$b("Goodness of Fit Test")),
                   verbatimTextOutput("goodness")),
            column(8,
                   plotOutput("pmf")
            )#closes column-8
          ),#closes fluidRow
          HTML("
")
       ) # closes column-8
    ) #closes fluidRow
  ) #closes fluidPage
), #close tabPanel#1

###################################################################################################
## tabPanel: Power Sequence                                                                     ##
###################################################################################################
tabPanel("(2) Power Sequence",
  fluidPage(

  # Give the page a title
  h3("Benford's Law: Power Sequence"),

  div("Note: Please adjust width of browser if only one column is visible.",br(),
  HTML("[Click here for another Shiny app on Benford's Law]"),
      style = "font-size: 9pt;color:teal"),br(),

  p("Consider a sequence of the form",
  HTML("b1, b2, …, b n, "),
  "where ", tags$em("b"), "is called the base.
  We will call this a ", HTML("power sequence."), "
  If you only consider the first digit of each number in a power sequence and examine its distribution,
  is it the case that it closely follows ",
  HTML("Benford's Law?"),
    "This app generates the power sequence, for a given", HTML("b and n,"),
    "and applies a goodness of fit test of the observed frequencies of first digits to Benford's Law.",
    style="font-size:11pt"),
  HTML("
"),

  fluidRow(

    column(4,wellPanel(

      sliderInput("pow.base",
                  label = h5(HTML("Base value (b)")),
                  min = 2, max = 9, value = 2, step=1),br(),

      sliderInput("pow.length",
                  label = h5(HTML("Length of sequence (n)")),
                  min = 150, max = 300, value = 150, step=10),br(),

      br(), br(), br(), br(),

      div("Shiny app by",
          a(href="http://statweb.calpoly.edu/jdoi/",target="_blank",
            "Jimmy Doi"),align="right", style = "font-size: 8pt"),

      div("Base R code by",
          a(href="http://statweb.calpoly.edu/jdoi/",target="_blank",
            "Jimmy Doi"),align="right", style = "font-size: 8pt"),

      div("Shiny source files:",
          a(href="https://gist.github.com/calpolystat/f4475cbfe4cc77cef168",
            target="_blank","GitHub Gist"),align="right", style = "font-size: 8pt"),

      div(a(href="http://www.statistics.calpoly.edu/shiny",target="_blank",
            "Cal Poly Statistics Dept Shiny Series"),align="right", style = "font-size: 8pt")
    )),
    column(8,
      div(span(tags$b("First 20 numbers in the sequence (first digit in"),style="font-size:9pt"),
          span(
            span("red",style="font-size:9pt; color:red; font-weight:bold"),tags$b("):",style="font-size:9pt")),
          style="font-size:0pt"),
      div(
        div(span(textOutput("e.num.1a"),style="font-size: 9pt; color:red; font-weight:bold; display:inline-block"),
            span(textOutput("e.num.1b"),style="font-size: 9pt; color:black; display:inline-block"),span(HTML(" "),style="font-size:9pt"),
            style="display:inline-block"),
        div(span(textOutput("e.num.2a"),style="font-size: 9pt; color:red; font-weight:bold; display:inline-block"),
            span(textOutput("e.num.2b"),style="font-size: 9pt; color:black; display:inline-block"),span(HTML(" "),style="font-size:9pt"),
            style="display:inline-block"),
        div(span(textOutput("e.num.3a"),style="font-size: 9pt; color:red; font-weight:bold; display:inline-block"),
            span(textOutput("e.num.3b"),style="font-size: 9pt; color:black; display:inline-block"),span(HTML(" "),style="font-size:9pt"),
            style="display:inline-block"),
        div(span(textOutput("e.num.4a"),style="font-size: 9pt; color:red; font-weight:bold; display:inline-block"),
            span(textOutput("e.num.4b"),style="font-size: 9pt; color:black; display:inline-block"),span(HTML(" "),style="font-size:9pt"),
            style="display:inline-block"),
        div(span(textOutput("e.num.5a"),style="font-size: 9pt; color:red; font-weight:bold; display:inline-block"),
            span(textOutput("e.num.5b"),style="font-size: 9pt; color:black; display:inline-block"),span(HTML(" "),style="font-size:9pt"),
            style="display:inline-block"),
        div(span(textOutput("e.num.6a"),style="font-size: 9pt; color:red; font-weight:bold; display:inline-block"),
            span(textOutput("e.num.6b"),style="font-size: 9pt; color:black; display:inline-block"),span(HTML(" "),style="font-size:9pt"),
            style="display:inline-block"),
        div(span(textOutput("e.num.7a"),style="font-size: 9pt; color:red; font-weight:bold; display:inline-block"),
            span(textOutput("e.num.7b"),style="font-size: 9pt; color:black; display:inline-block"),span(HTML(" "),style="font-size:9pt"),
            style="display:inline-block"),
        div(span(textOutput("e.num.8a"),style="font-size: 9pt; color:red; font-weight:bold; display:inline-block"),
            span(textOutput("e.num.8b"),style="font-size: 9pt; color:black; display:inline-block"),span(HTML(" "),style="font-size:9pt"),
            style="display:inline-block"),
        div(span(textOutput("e.num.9a"),style="font-size: 9pt; color:red; font-weight:bold; display:inline-block"),
            span(textOutput("e.num.9b"),style="font-size: 9pt; color:black; display:inline-block"),span(HTML(" "),style="font-size:9pt"),
            style="display:inline-block"),
        div(span(textOutput("e.num.10a"),style="font-size: 9pt; color:red; font-weight:bold; display:inline-block"),
            span(textOutput("e.num.10b"),style="font-size: 9pt; color:black; display:inline-block"),span(HTML(" "),style="font-size:9pt"),
            style="display:inline-block"),
        div(span(textOutput("e.num.11a"),style="font-size: 9pt; color:red; font-weight:bold; display:inline-block"),
            span(textOutput("e.num.11b"),style="font-size: 9pt; color:black; display:inline-block"),span(HTML(" "),style="font-size:9pt"),
            style="display:inline-block"),
        div(span(textOutput("e.num.12a"),style="font-size: 9pt; color:red; font-weight:bold; display:inline-block"),
            span(textOutput("e.num.12b"),style="font-size: 9pt; color:black; display:inline-block"),span(HTML(" "),style="font-size:9pt"),
            style="display:inline-block"),
        div(span(textOutput("e.num.13a"),style="font-size: 9pt; color:red; font-weight:bold; display:inline-block"),
            span(textOutput("e.num.13b"),style="font-size: 9pt; color:black; display:inline-block"),span(HTML(" "),style="font-size:9pt"),
            style="display:inline-block"),
        div(span(textOutput("e.num.14a"),style="font-size: 9pt; color:red; font-weight:bold; display:inline-block"),
            span(textOutput("e.num.14b"),style="font-size: 9pt; color:black; display:inline-block"),span(HTML(" "),style="font-size:9pt"),
            style="display:inline-block"),
        div(span(textOutput("e.num.15a"),style="font-size: 9pt; color:red; font-weight:bold; display:inline-block"),
            span(textOutput("e.num.15b"),style="font-size: 9pt; color:black; display:inline-block"),span(HTML(" "),style="font-size:9pt"),
            style="display:inline-block"),
        div(span(textOutput("e.num.16a"),style="font-size: 9pt; color:red; font-weight:bold; display:inline-block"),
            span(textOutput("e.num.16b"),style="font-size: 9pt; color:black; display:inline-block"),span(HTML(" "),style="font-size:9pt"),
            style="display:inline-block"),
        div(span(textOutput("e.num.17a"),style="font-size: 9pt; color:red; font-weight:bold; display:inline-block"),
            span(textOutput("e.num.17b"),style="font-size: 9pt; color:black; display:inline-block"),span(HTML(" "),style="font-size:9pt"),
            style="display:inline-block"),
        div(span(textOutput("e.num.18a"),style="font-size: 9pt; color:red; font-weight:bold; display:inline-block"),
            span(textOutput("e.num.18b"),style="font-size: 9pt; color:black; display:inline-block"),span(HTML(" "),style="font-size:9pt"),
            style="display:inline-block"),
        div(span(textOutput("e.num.19a"),style="font-size: 9pt; color:red; font-weight:bold; display:inline-block"),
            span(textOutput("e.num.19b"),style="font-size: 9pt; color:black; display:inline-block"),span(HTML(" "),style="font-size:9pt"),
            style="display:inline-block"),
        div(span(textOutput("e.num.20a"),style="font-size: 9pt; color:red; font-weight:bold; display:inline-block"),
            span(textOutput("e.num.20b"),style="font-size: 9pt; color:black; display:inline-block"),span(HTML(" "),style="font-size:9pt"),
            span("",style="font-size: 9pt"),style="display:inline-block"),
        style="font-size:0;"),
      div(span("[Sequence has ",style="font-size:9pt;display:inline-block"),
          span(HTML(" "),style="font-size:9pt"),
          span(textOutput("powlength"),style="font-size:9pt;display:inline-block;color:teal"),
          span(HTML(" "),style="font-size:9pt"),
          span("numbers total]",style="font-size:9pt;display:inline-block"),style="font-size:0pt;display:inline-block;",align="right"),

      HTML("
"),
      fluidRow(
        column(4,
               p(tags$b("Goodness of Fit Test")),
               verbatimTextOutput("e.goodness")),
        column(8,
               plotOutput("e.pmf")
              ) #closes column-8
            ), #closes fluidRow
          HTML("
")
        ) #closes column-8
     ) #closes fluidRow
  ) #closes fluidPage
), #close tabPanel#2

###################################################################################################
## tabPanel: Prime Numbers Sequence                                                              ##
###################################################################################################
tabPanel("(3) Prime Numbers Sequence",
  fluidPage(

    # Give the page a title
    h3("Generalized Benford's Law: Prime Numbers Sequence"),

    div("Note: Please adjust width of browser if only one column is visible.",br(),
        HTML("[Click here for another Shiny app on Benford's Law]"),
        style = "font-size: 9pt;color:teal"),br(),

    p("Consider the sequence of prime numbers less than or equal to some power of 10. An article from 2009
      shows that the distribution of the first digit of these prime numbers
      is well described by what's known as", HTML("Generalized Benford's Law (GBL)"),".
      This app generates the prime numbers less than or equal to", HTML("103, 104,
      105, or 106"), "and applies a goodness of fit test of the observed frequencies of first digits to GBL."
      ),

    p("More information on the Generalized Benford's Law can be found in the following journal article:"),

    div("Luque, B. and Lacasa, L.(2009)",
        HTML("'The first-digit frequencies of prime numbers and Riemann zeta zeros'"),
        em("Proc. R. Soc. A"),", 465, 2197-2216", style="padding-left: 20px; display:block; border-left: 5px solid #faebbc;margin-left:0px"),

    HTML("
"),

    # Generate a row with a sidebar
    fluidRow(

      column(4,wellPanel(

        selectInput("my.n", label = h5("Generate sequence of prime numbers less than or equal to"),
                    choices = list("1,000" = 1000, "10,000" = 10000, "100,000" = 100000, "1,000,000" = 1000000),
                    selected = 1000),

        br(), br(), br(), br(),

        div("Shiny app by",
            a(href="http://statweb.calpoly.edu/jdoi/",target="_blank",
              "Jimmy Doi"),align="right", style = "font-size: 8pt"),

        div("Base R code by",
            a(href="http://statweb.calpoly.edu/jdoi/",target="_blank",
              "Jimmy Doi"),align="right", style = "font-size: 8pt"),

        div("Shiny source files:",
            a(href="https://gist.github.com/calpolystat/f4475cbfe4cc77cef168",
              target="_blank","GitHub Gist"),align="right", style = "font-size: 8pt"),

        div(a(href="http://www.statistics.calpoly.edu/shiny",target="_blank",
              "Cal Poly Statistics Dept Shiny Series"),align="right", style = "font-size: 8pt")
      )),
      column(8,
        div(span(tags$b("First 80 numbers in the sequence (first digit in"),style="font-size:9pt"),
            span(
              span("red",style="font-size:9pt; color:red; font-weight:bold"),tags$b("):",style="font-size:9pt")),
            style="font-size:0pt"),
        div(
          div(span(textOutput("pr.num.1a"),style="font-size: 9pt; color:red; font-weight:bold; display:inline-block"),
              span(textOutput("pr.num.1b"),style="font-size: 9pt; color:black; display:inline-block"),span(HTML(" "),style="font-size:9pt"),
              style="display:inline-block"),
          div(span(textOutput("pr.num.2a"),style="font-size: 9pt; color:red; font-weight:bold; display:inline-block"),
              span(textOutput("pr.num.2b"),style="font-size: 9pt; color:black; display:inline-block"),span(HTML(" "),style="font-size:9pt"),
              style="display:inline-block"),
          div(span(textOutput("pr.num.3a"),style="font-size: 9pt; color:red; font-weight:bold; display:inline-block"),
              span(textOutput("pr.num.3b"),style="font-size: 9pt; color:black; display:inline-block"),span(HTML(" "),style="font-size:9pt"),
              style="display:inline-block"),
          div(span(textOutput("pr.num.4a"),style="font-size: 9pt; color:red; font-weight:bold; display:inline-block"),
              span(textOutput("pr.num.4b"),style="font-size: 9pt; color:black; display:inline-block"),span(HTML(" "),style="font-size:9pt"),
              style="display:inline-block"),
          div(span(textOutput("pr.num.5a"),style="font-size: 9pt; color:red; font-weight:bold; display:inline-block"),
              span(textOutput("pr.num.5b"),style="font-size: 9pt; color:black; display:inline-block"),span(HTML(" "),style="font-size:9pt"),
              style="display:inline-block"),
          div(span(textOutput("pr.num.6a"),style="font-size: 9pt; color:red; font-weight:bold; display:inline-block"),
              span(textOutput("pr.num.6b"),style="font-size: 9pt; color:black; display:inline-block"),span(HTML(" "),style="font-size:9pt"),
              style="display:inline-block"),
          div(span(textOutput("pr.num.7a"),style="font-size: 9pt; color:red; font-weight:bold; display:inline-block"),
              span(textOutput("pr.num.7b"),style="font-size: 9pt; color:black; display:inline-block"),span(HTML(" "),style="font-size:9pt"),
              style="display:inline-block"),
          div(span(textOutput("pr.num.8a"),style="font-size: 9pt; color:red; font-weight:bold; display:inline-block"),
              span(textOutput("pr.num.8b"),style="font-size: 9pt; color:black; display:inline-block"),span(HTML(" "),style="font-size:9pt"),
              style="display:inline-block"),
          div(span(textOutput("pr.num.9a"),style="font-size: 9pt; color:red; font-weight:bold; display:inline-block"),
              span(textOutput("pr.num.9b"),style="font-size: 9pt; color:black; display:inline-block"),span(HTML(" "),style="font-size:9pt"),
              style="display:inline-block"),
          div(span(textOutput("pr.num.10a"),style="font-size: 9pt; color:red; font-weight:bold; display:inline-block"),
              span(textOutput("pr.num.10b"),style="font-size: 9pt; color:black; display:inline-block"),span(HTML(" "),style="font-size:9pt"),
              style="display:inline-block"),
          div(span(textOutput("pr.num.11a"),style="font-size: 9pt; color:red; font-weight:bold; display:inline-block"),
              span(textOutput("pr.num.11b"),style="font-size: 9pt; color:black; display:inline-block"),span(HTML(" "),style="font-size:9pt"),
              style="display:inline-block"),
          div(span(textOutput("pr.num.12a"),style="font-size: 9pt; color:red; font-weight:bold; display:inline-block"),
              span(textOutput("pr.num.12b"),style="font-size: 9pt; color:black; display:inline-block"),span(HTML(" "),style="font-size:9pt"),
              style="display:inline-block"),
          div(span(textOutput("pr.num.13a"),style="font-size: 9pt; color:red; font-weight:bold; display:inline-block"),
              span(textOutput("pr.num.13b"),style="font-size: 9pt; color:black; display:inline-block"),span(HTML(" "),style="font-size:9pt"),
              style="display:inline-block"),
          div(span(textOutput("pr.num.14a"),style="font-size: 9pt; color:red; font-weight:bold; display:inline-block"),
              span(textOutput("pr.num.14b"),style="font-size: 9pt; color:black; display:inline-block"),span(HTML(" "),style="font-size:9pt"),
              style="display:inline-block"),
          div(span(textOutput("pr.num.15a"),style="font-size: 9pt; color:red; font-weight:bold; display:inline-block"),
              span(textOutput("pr.num.15b"),style="font-size: 9pt; color:black; display:inline-block"),span(HTML(" "),style="font-size:9pt"),
              style="display:inline-block"),
          div(span(textOutput("pr.num.16a"),style="font-size: 9pt; color:red; font-weight:bold; display:inline-block"),
              span(textOutput("pr.num.16b"),style="font-size: 9pt; color:black; display:inline-block"),span(HTML(" "),style="font-size:9pt"),
              style="display:inline-block"),
          div(span(textOutput("pr.num.17a"),style="font-size: 9pt; color:red; font-weight:bold; display:inline-block"),
              span(textOutput("pr.num.17b"),style="font-size: 9pt; color:black; display:inline-block"),span(HTML(" "),style="font-size:9pt"),
              style="display:inline-block"),
          div(span(textOutput("pr.num.18a"),style="font-size: 9pt; color:red; font-weight:bold; display:inline-block"),
              span(textOutput("pr.num.18b"),style="font-size: 9pt; color:black; display:inline-block"),span(HTML(" "),style="font-size:9pt"),
              style="display:inline-block"),
          div(span(textOutput("pr.num.19a"),style="font-size: 9pt; color:red; font-weight:bold; display:inline-block"),
              span(textOutput("pr.num.19b"),style="font-size: 9pt; color:black; display:inline-block"),span(HTML(" "),style="font-size:9pt"),
              style="display:inline-block"),
          div(span(textOutput("pr.num.20a"),style="font-size: 9pt; color:red; font-weight:bold; display:inline-block"),
              span(textOutput("pr.num.20b"),style="font-size: 9pt; color:black; display:inline-block"),span(HTML(" "),style="font-size:9pt"),
              style="display:inline-block"),
          div(span(textOutput("pr.num.21a"),style="font-size: 9pt; color:red; font-weight:bold; display:inline-block"),
              span(textOutput("pr.num.21b"),style="font-size: 9pt; color:black; display:inline-block"),span(HTML(" "),style="font-size:9pt"),
              style="display:inline-block"),
          div(span(textOutput("pr.num.22a"),style="font-size: 9pt; color:red; font-weight:bold; display:inline-block"),
              span(textOutput("pr.num.22b"),style="font-size: 9pt; color:black; display:inline-block"),span(HTML(" "),style="font-size:9pt"),
              style="display:inline-block"),
          div(span(textOutput("pr.num.23a"),style="font-size: 9pt; color:red; font-weight:bold; display:inline-block"),
              span(textOutput("pr.num.23b"),style="font-size: 9pt; color:black; display:inline-block"),span(HTML(" "),style="font-size:9pt"),
              style="display:inline-block"),
          div(span(textOutput("pr.num.24a"),style="font-size: 9pt; color:red; font-weight:bold; display:inline-block"),
              span(textOutput("pr.num.24b"),style="font-size: 9pt; color:black; display:inline-block"),span(HTML(" "),style="font-size:9pt"),
              style="display:inline-block"),
          div(span(textOutput("pr.num.25a"),style="font-size: 9pt; color:red; font-weight:bold; display:inline-block"),
              span(textOutput("pr.num.25b"),style="font-size: 9pt; color:black; display:inline-block"),span(HTML(" "),style="font-size:9pt"),
              style="display:inline-block"),
          div(span(textOutput("pr.num.26a"),style="font-size: 9pt; color:red; font-weight:bold; display:inline-block"),
              span(textOutput("pr.num.26b"),style="font-size: 9pt; color:black; display:inline-block"),span(HTML(" "),style="font-size:9pt"),
              style="display:inline-block"),
          div(span(textOutput("pr.num.27a"),style="font-size: 9pt; color:red; font-weight:bold; display:inline-block"),
              span(textOutput("pr.num.27b"),style="font-size: 9pt; color:black; display:inline-block"),span(HTML(" "),style="font-size:9pt"),
              style="display:inline-block"),
          div(span(textOutput("pr.num.28a"),style="font-size: 9pt; color:red; font-weight:bold; display:inline-block"),
              span(textOutput("pr.num.28b"),style="font-size: 9pt; color:black; display:inline-block"),span(HTML(" "),style="font-size:9pt"),
              style="display:inline-block"),
          div(span(textOutput("pr.num.29a"),style="font-size: 9pt; color:red; font-weight:bold; display:inline-block"),
              span(textOutput("pr.num.29b"),style="font-size: 9pt; color:black; display:inline-block"),span(HTML(" "),style="font-size:9pt"),
              style="display:inline-block"),
          div(span(textOutput("pr.num.30a"),style="font-size: 9pt; color:red; font-weight:bold; display:inline-block"),
              span(textOutput("pr.num.30b"),style="font-size: 9pt; color:black; display:inline-block"),span(HTML(" "),style="font-size:9pt"),
              style="display:inline-block"),
          div(span(textOutput("pr.num.31a"),style="font-size: 9pt; color:red; font-weight:bold; display:inline-block"),
              span(textOutput("pr.num.31b"),style="font-size: 9pt; color:black; display:inline-block"),span(HTML(" "),style="font-size:9pt"),
              style="display:inline-block"),
          div(span(textOutput("pr.num.32a"),style="font-size: 9pt; color:red; font-weight:bold; display:inline-block"),
              span(textOutput("pr.num.32b"),style="font-size: 9pt; color:black; display:inline-block"),span(HTML(" "),style="font-size:9pt"),
              style="display:inline-block"),
          div(span(textOutput("pr.num.33a"),style="font-size: 9pt; color:red; font-weight:bold; display:inline-block"),
              span(textOutput("pr.num.33b"),style="font-size: 9pt; color:black; display:inline-block"),span(HTML(" "),style="font-size:9pt"),
              style="display:inline-block"),
          div(span(textOutput("pr.num.34a"),style="font-size: 9pt; color:red; font-weight:bold; display:inline-block"),
              span(textOutput("pr.num.34b"),style="font-size: 9pt; color:black; display:inline-block"),span(HTML(" "),style="font-size:9pt"),
              style="display:inline-block"),
          div(span(textOutput("pr.num.35a"),style="font-size: 9pt; color:red; font-weight:bold; display:inline-block"),
              span(textOutput("pr.num.35b"),style="font-size: 9pt; color:black; display:inline-block"),span(HTML(" "),style="font-size:9pt"),
              style="display:inline-block"),
          div(span(textOutput("pr.num.36a"),style="font-size: 9pt; color:red; font-weight:bold; display:inline-block"),
              span(textOutput("pr.num.36b"),style="font-size: 9pt; color:black; display:inline-block"),span(HTML(" "),style="font-size:9pt"),
              style="display:inline-block"),
          div(span(textOutput("pr.num.37a"),style="font-size: 9pt; color:red; font-weight:bold; display:inline-block"),
              span(textOutput("pr.num.37b"),style="font-size: 9pt; color:black; display:inline-block"),span(HTML(" "),style="font-size:9pt"),
              style="display:inline-block"),
          div(span(textOutput("pr.num.38a"),style="font-size: 9pt; color:red; font-weight:bold; display:inline-block"),
              span(textOutput("pr.num.38b"),style="font-size: 9pt; color:black; display:inline-block"),span(HTML(" "),style="font-size:9pt"),
              style="display:inline-block"),
          div(span(textOutput("pr.num.39a"),style="font-size: 9pt; color:red; font-weight:bold; display:inline-block"),
              span(textOutput("pr.num.39b"),style="font-size: 9pt; color:black; display:inline-block"),span(HTML(" "),style="font-size:9pt"),
              style="display:inline-block"),
          div(span(textOutput("pr.num.40a"),style="font-size: 9pt; color:red; font-weight:bold; display:inline-block"),
              span(textOutput("pr.num.40b"),style="font-size: 9pt; color:black; display:inline-block"),span(HTML(" "),style="font-size:9pt"),
              style="display:inline-block"),
          div(span(textOutput("pr.num.41a"),style="font-size: 9pt; color:red; font-weight:bold; display:inline-block"),
              span(textOutput("pr.num.41b"),style="font-size: 9pt; color:black; display:inline-block"),span(HTML(" "),style="font-size:9pt"),
              style="display:inline-block"),
          div(span(textOutput("pr.num.42a"),style="font-size: 9pt; color:red; font-weight:bold; display:inline-block"),
              span(textOutput("pr.num.42b"),style="font-size: 9pt; color:black; display:inline-block"),span(HTML(" "),style="font-size:9pt"),
              style="display:inline-block"),
          div(span(textOutput("pr.num.43a"),style="font-size: 9pt; color:red; font-weight:bold; display:inline-block"),
              span(textOutput("pr.num.43b"),style="font-size: 9pt; color:black; display:inline-block"),span(HTML(" "),style="font-size:9pt"),
              style="display:inline-block"),
          div(span(textOutput("pr.num.44a"),style="font-size: 9pt; color:red; font-weight:bold; display:inline-block"),
              span(textOutput("pr.num.44b"),style="font-size: 9pt; color:black; display:inline-block"),span(HTML(" "),style="font-size:9pt"),
              style="display:inline-block"),
          div(span(textOutput("pr.num.45a"),style="font-size: 9pt; color:red; font-weight:bold; display:inline-block"),
              span(textOutput("pr.num.45b"),style="font-size: 9pt; color:black; display:inline-block"),span(HTML(" "),style="font-size:9pt"),
              style="display:inline-block"),
          div(span(textOutput("pr.num.46a"),style="font-size: 9pt; color:red; font-weight:bold; display:inline-block"),
              span(textOutput("pr.num.46b"),style="font-size: 9pt; color:black; display:inline-block"),span(HTML(" "),style="font-size:9pt"),
              style="display:inline-block"),
          div(span(textOutput("pr.num.47a"),style="font-size: 9pt; color:red; font-weight:bold; display:inline-block"),
              span(textOutput("pr.num.47b"),style="font-size: 9pt; color:black; display:inline-block"),span(HTML(" "),style="font-size:9pt"),
              style="display:inline-block"),
          div(span(textOutput("pr.num.48a"),style="font-size: 9pt; color:red; font-weight:bold; display:inline-block"),
              span(textOutput("pr.num.48b"),style="font-size: 9pt; color:black; display:inline-block"),span(HTML(" "),style="font-size:9pt"),
              style="display:inline-block"),
          div(span(textOutput("pr.num.49a"),style="font-size: 9pt; color:red; font-weight:bold; display:inline-block"),
              span(textOutput("pr.num.49b"),style="font-size: 9pt; color:black; display:inline-block"),span(HTML(" "),style="font-size:9pt"),
              style="display:inline-block"),
          div(span(textOutput("pr.num.50a"),style="font-size: 9pt; color:red; font-weight:bold; display:inline-block"),
              span(textOutput("pr.num.50b"),style="font-size: 9pt; color:black; display:inline-block"),span(HTML(" "),style="font-size:9pt"),
              style="display:inline-block"),
          div(span(textOutput("pr.num.51a"),style="font-size: 9pt; color:red; font-weight:bold; display:inline-block"),
              span(textOutput("pr.num.51b"),style="font-size: 9pt; color:black; display:inline-block"),span(HTML(" "),style="font-size:9pt"),
              style="display:inline-block"),
          div(span(textOutput("pr.num.52a"),style="font-size: 9pt; color:red; font-weight:bold; display:inline-block"),
              span(textOutput("pr.num.52b"),style="font-size: 9pt; color:black; display:inline-block"),span(HTML(" "),style="font-size:9pt"),
              style="display:inline-block"),
          div(span(textOutput("pr.num.53a"),style="font-size: 9pt; color:red; font-weight:bold; display:inline-block"),
              span(textOutput("pr.num.53b"),style="font-size: 9pt; color:black; display:inline-block"),span(HTML(" "),style="font-size:9pt"),
              style="display:inline-block"),
          div(span(textOutput("pr.num.54a"),style="font-size: 9pt; color:red; font-weight:bold; display:inline-block"),
              span(textOutput("pr.num.54b"),style="font-size: 9pt; color:black; display:inline-block"),span(HTML(" "),style="font-size:9pt"),
              style="display:inline-block"),
          div(span(textOutput("pr.num.55a"),style="font-size: 9pt; color:red; font-weight:bold; display:inline-block"),
              span(textOutput("pr.num.55b"),style="font-size: 9pt; color:black; display:inline-block"),span(HTML(" "),style="font-size:9pt"),
              style="display:inline-block"),
          div(span(textOutput("pr.num.56a"),style="font-size: 9pt; color:red; font-weight:bold; display:inline-block"),
              span(textOutput("pr.num.56b"),style="font-size: 9pt; color:black; display:inline-block"),span(HTML(" "),style="font-size:9pt"),
              style="display:inline-block"),
          div(span(textOutput("pr.num.57a"),style="font-size: 9pt; color:red; font-weight:bold; display:inline-block"),
              span(textOutput("pr.num.57b"),style="font-size: 9pt; color:black; display:inline-block"),span(HTML(" "),style="font-size:9pt"),
              style="display:inline-block"),
          div(span(textOutput("pr.num.58a"),style="font-size: 9pt; color:red; font-weight:bold; display:inline-block"),
              span(textOutput("pr.num.58b"),style="font-size: 9pt; color:black; display:inline-block"),span(HTML(" "),style="font-size:9pt"),
              style="display:inline-block"),
          div(span(textOutput("pr.num.59a"),style="font-size: 9pt; color:red; font-weight:bold; display:inline-block"),
              span(textOutput("pr.num.59b"),style="font-size: 9pt; color:black; display:inline-block"),span(HTML(" "),style="font-size:9pt"),
              style="display:inline-block"),
          div(span(textOutput("pr.num.60a"),style="font-size: 9pt; color:red; font-weight:bold; display:inline-block"),
              span(textOutput("pr.num.60b"),style="font-size: 9pt; color:black; display:inline-block"),span(HTML(" "),style="font-size:9pt"),
              style="display:inline-block"),
          div(span(textOutput("pr.num.61a"),style="font-size: 9pt; color:red; font-weight:bold; display:inline-block"),
              span(textOutput("pr.num.61b"),style="font-size: 9pt; color:black; display:inline-block"),span(HTML(" "),style="font-size:9pt"),
              style="display:inline-block"),
          div(span(textOutput("pr.num.62a"),style="font-size: 9pt; color:red; font-weight:bold; display:inline-block"),
              span(textOutput("pr.num.62b"),style="font-size: 9pt; color:black; display:inline-block"),span(HTML(" "),style="font-size:9pt"),
              style="display:inline-block"),
          div(span(textOutput("pr.num.63a"),style="font-size: 9pt; color:red; font-weight:bold; display:inline-block"),
              span(textOutput("pr.num.63b"),style="font-size: 9pt; color:black; display:inline-block"),span(HTML(" "),style="font-size:9pt"),
              style="display:inline-block"),
          div(span(textOutput("pr.num.64a"),style="font-size: 9pt; color:red; font-weight:bold; display:inline-block"),
              span(textOutput("pr.num.64b"),style="font-size: 9pt; color:black; display:inline-block"),span(HTML(" "),style="font-size:9pt"),
              style="display:inline-block"),
          div(span(textOutput("pr.num.65a"),style="font-size: 9pt; color:red; font-weight:bold; display:inline-block"),
              span(textOutput("pr.num.65b"),style="font-size: 9pt; color:black; display:inline-block"),span(HTML(" "),style="font-size:9pt"),
              style="display:inline-block"),
          div(span(textOutput("pr.num.66a"),style="font-size: 9pt; color:red; font-weight:bold; display:inline-block"),
              span(textOutput("pr.num.66b"),style="font-size: 9pt; color:black; display:inline-block"),span(HTML(" "),style="font-size:9pt"),
              style="display:inline-block"),
          div(span(textOutput("pr.num.67a"),style="font-size: 9pt; color:red; font-weight:bold; display:inline-block"),
              span(textOutput("pr.num.67b"),style="font-size: 9pt; color:black; display:inline-block"),span(HTML(" "),style="font-size:9pt"),
              style="display:inline-block"),
          div(span(textOutput("pr.num.68a"),style="font-size: 9pt; color:red; font-weight:bold; display:inline-block"),
              span(textOutput("pr.num.68b"),style="font-size: 9pt; color:black; display:inline-block"),span(HTML(" "),style="font-size:9pt"),
              style="display:inline-block"),
          div(span(textOutput("pr.num.69a"),style="font-size: 9pt; color:red; font-weight:bold; display:inline-block"),
              span(textOutput("pr.num.69b"),style="font-size: 9pt; color:black; display:inline-block"),span(HTML(" "),style="font-size:9pt"),
              style="display:inline-block"),
          div(span(textOutput("pr.num.70a"),style="font-size: 9pt; color:red; font-weight:bold; display:inline-block"),
              span(textOutput("pr.num.70b"),style="font-size: 9pt; color:black; display:inline-block"),span(HTML(" "),style="font-size:9pt"),
              style="display:inline-block"),
          div(span(textOutput("pr.num.71a"),style="font-size: 9pt; color:red; font-weight:bold; display:inline-block"),
              span(textOutput("pr.num.71b"),style="font-size: 9pt; color:black; display:inline-block"),span(HTML(" "),style="font-size:9pt"),
              style="display:inline-block"),
          div(span(textOutput("pr.num.72a"),style="font-size: 9pt; color:red; font-weight:bold; display:inline-block"),
              span(textOutput("pr.num.72b"),style="font-size: 9pt; color:black; display:inline-block"),span(HTML(" "),style="font-size:9pt"),
              style="display:inline-block"),
          div(span(textOutput("pr.num.73a"),style="font-size: 9pt; color:red; font-weight:bold; display:inline-block"),
              span(textOutput("pr.num.73b"),style="font-size: 9pt; color:black; display:inline-block"),span(HTML(" "),style="font-size:9pt"),
              style="display:inline-block"),
          div(span(textOutput("pr.num.74a"),style="font-size: 9pt; color:red; font-weight:bold; display:inline-block"),
              span(textOutput("pr.num.74b"),style="font-size: 9pt; color:black; display:inline-block"),span(HTML(" "),style="font-size:9pt"),
              style="display:inline-block"),
          div(span(textOutput("pr.num.75a"),style="font-size: 9pt; color:red; font-weight:bold; display:inline-block"),
              span(textOutput("pr.num.75b"),style="font-size: 9pt; color:black; display:inline-block"),span(HTML(" "),style="font-size:9pt"),
              style="display:inline-block"),
          div(span(textOutput("pr.num.76a"),style="font-size: 9pt; color:red; font-weight:bold; display:inline-block"),
              span(textOutput("pr.num.76b"),style="font-size: 9pt; color:black; display:inline-block"),span(HTML(" "),style="font-size:9pt"),
              style="display:inline-block"),
          div(span(textOutput("pr.num.77a"),style="font-size: 9pt; color:red; font-weight:bold; display:inline-block"),
              span(textOutput("pr.num.77b"),style="font-size: 9pt; color:black; display:inline-block"),span(HTML(" "),style="font-size:9pt"),
              style="display:inline-block"),
          div(span(textOutput("pr.num.78a"),style="font-size: 9pt; color:red; font-weight:bold; display:inline-block"),
              span(textOutput("pr.num.78b"),style="font-size: 9pt; color:black; display:inline-block"),span(HTML(" "),style="font-size:9pt"),
              style="display:inline-block"),
          div(span(textOutput("pr.num.79a"),style="font-size: 9pt; color:red; font-weight:bold; display:inline-block"),
              span(textOutput("pr.num.79b"),style="font-size: 9pt; color:black; display:inline-block"),span(HTML(" "),style="font-size:9pt"),
              style="display:inline-block"),
          div(span(textOutput("pr.num.80a"),style="font-size: 9pt; color:red; font-weight:bold; display:inline-block"),
              span(textOutput("pr.num.80b"),style="font-size: 9pt; color:black; display:inline-block"),span(HTML(" "),style="font-size:9pt"),
              style="display:inline-block"),
          style="font-size:0;"),
        div(span("[Sequence has ",style="font-size:9pt;display:inline-block"),
            span(HTML(" "),style="font-size:9pt"),
            span(textOutput("num.primes"),style="font-size:9pt;display:inline-block;color:teal"),
            span(HTML(" "),style="font-size:9pt"),
            span("prime numbers total]",style="font-size:9pt;display:inline-block"),style="font-size:0pt;display:inline-block;",align="right"),

        HTML("
"),
        fluidRow(
          column(4,
                 p(tags$b("Goodness of Fit Test")),
                 verbatimTextOutput("pr.goodness")),
          column(8,
                 plotOutput("pr.pmf")
              ) # closes column-8
            ), #closes fluidRow
          HTML("
")
        ) #closes column-8
     ) #closes fluidRow
  ) #closes fluidPage
) #closes tabPanel#3
) #closes navbarPage
) #closes shinyUI


r_pacf_1 = ARMAacf(ar=c(1.3, -0.24), lag.max=20, pacf=TRUE)
print('For AR(2) process')
cat('l=1',r_pacf_1[1])
cat('l=2',r_pacf_1[2])

r_pacf_2 = ARMAacf(ma=c(0.6), lag.max=20, pacf=TRUE)
print('For MA(1) process')
cat('l=1',r_pacf_2[1])
cat('l=2',r_pacf_2[2])


blkwin <- function(np) {
  rad <- seq(0,2*pi,2*pi/(np-1))
  w <- (.42 - .5*cos(rad) + .08*cos(2*rad))
  return(w)
}

hamwin <- function(np) {
  w <- .54 - .46 * cos(seq(0,2*pi,2*pi/(np-1)))
  return(w)
}

hanwin <- function(np) {
  w <- .5 - .5 * cos(seq(0,2*pi,2*pi/(np-1)))
  return(w)
}


# Example : 6   Chapter : 8.6     Page No: 457
# Singualar Value Decomposition
gradematrixA<-matrix(c(-6,0,4,2,2,4,0,-6,0,-6,2,4,4,2,-6,0),ncol=4)
print("SVD of Grade matrix is")
print(svd(gradematrixA))
#The answers may vary due to rounding off values


=begin
  # sample-diagonalization01.rb

  require "algebra"
  M = SquareMatrix(Rational, 3)
  a = M[[1,-1,-1], [-1,1,-1], [2,1,-1]]
  puts "A = "; a.display; puts
  #A =
  #  1,  -1,  -1
  # -1,   1,  -1
  #  2,   1,  -1

  e = a.diagonalize

  puts "Charactoristic Poly.: #{e.chpoly} => #{e.facts}";puts
  #Charactoristic Poly.: t^3 - t^2 + t - 6 => (t - 2)(t^2 + t + 3)

  puts "Algebraic Numbers:"
  e.roots.each do |po, rs|
    puts "#{rs.join(', ')} : roots of #{po} == 0"
  end; puts
  #Algebraic Numbers:
  #a, -a - 1 : roots of t^2 + t + 3 == 0

  puts "EigenSpaces: "
  e.evalues.uniq.each do |ev|
    puts "W_{#{ev}} = <#{e.espaces[ev].join(', ')}>"
  end; puts
  #EigenSpaces:
  #W_{2} = <[4, -5, 1]>
  #W_{a} = <[1/3a + 1/3, 1/3a + 1/3, 1]>
  #W_{-a - 1} = <[-1/3a, -1/3a, 1]>

  puts "Trans. Matrix:"
  puts "P ="
  e.tmatrix.display; puts
  puts "P^-1 * A * P = "; (e.tmatrix.inverse * a * e.tmatrix).display; puts
  #P =
  #  4, 1/3a + 1/3, -1/3a
  # -5, 1/3a + 1/3, -1/3a
  #  1,   1,   1
  #
  #P^-1 * A * P =
  #  2,   0,   0
  #  0,   a,   0
  #  0,   0, -a - 1
((<_|CONTENTS>))
=end


f <- function(x) (x + 3)^2
f <- Vectorize(f)
lf <- function(x) log(f(x))
lf <- Vectorize(lf)

lf_prime_num <- function(x) numDeriv::grad(lf, x)

lf_prime_analytical <- function(x) (2*(x+3))/f(x)

curve(lf_prime_num(x), 0, 10)
curve(lf_prime_analytical(x), 0 , 10, lwd = 2, lty = 2, col = 2, add = TRUE)


horner <- function(a, x) {
  iv <- 0
  for(i in length(a):1) {
    iv <- iv * x + a[i]
  }
  iv
}

cat(horner(c(-19, 7, -4, 6), 3), "\n")


# Util

standard_error <- function(X, y, robust){
    if (robust %in% c("White", "white", "HC0")) {
        std_error <- robust_stde0(X, y)
        cov_type <- "heteroskadestic (White)"
    } else if (robust %in% c("Hinkley", "hinkley", "HC1")) {
        std_error <- robust_stde1(X, y)
        cov_type <- "heteroskadestic (Hinkley)"
    } else if (robust %in% c("Horn", "horn", "HC2")) {
        std_error <- robust_stde2(X, y)
        cov_type <- "heteroskadestic (Horn)"
    } else if (robust %in% c("MacKinnon", "mackinnon", "HC3")) {
        std_error <- robust_stde3(X, y)
        cov_type <- "heteroskadestic (MacKinnon)"
    } else {
        std_error <- stde(X, y)
        cov_type <- "homoskadestic"
    }
    return(list("value"=std_error, "cov_type"=cov_type))
}

# Formula

#' @export
homoskedastic_standard_error <- function(X, y){
    diag(homoskedastic_covariance_estimator(X, y))^(1/2)
}

#' @export
white_heteroskedastic_standard_error <- function(X, y){
    diag(white_heteroskedastic_covariance_estimator(X, y))^(1/2)
}

#' @export
hinkley_heteroskedastic_standard_error <- function(X, y){
    diag(hinkley_heteroskedastic_covariance_estimator(X, y))^(1/2)
}

#' @export
horn_heteroskedastic_standard_error <- function(X, y){
    diag(horn_heteroskedastic_covariance_estimator(X, y))^(1/2)
}

#' @export
mackinnon_heteroskedastic_standard_error <- function(X, y){
    diag(mackinnon_heteroskedastic_covariance_estimator(X, y))^(1/2)
}

# Abbreviation

#' @export
stde <- homoskedastic_standard_error

#' @export
robust_stde0 <- white_heteroskedastic_standard_error

#' @export
robust_stde1 <- hinkley_heteroskedastic_standard_error

#' @export
robust_stde2 <- horn_heteroskedastic_standard_error

#' @export
robust_stde3 <- mackinnon_heteroskedastic_standard_error


png("#49_custom_pie_plot.png" , width = 480, height = 480 )

#Data

x <- c(15, 9, 75, 90, 1, 1, 11, 5, 9, 8, 33, 11, 11, 20, 14, 13, 10, 28, 33, 21, 24, 25, 11, 33)

#Fonction clock plot
clock.plot <- function (x, col = rainbow(n), ...) {
  if( min(x)<0 ) x <- x - min(x)
  if( max(x)>1 ) x <- x/max(x)
  n <- length(x)
  if(is.null(names(x))) names(x) <- 0:(n-1)
  m <- 1.05
  plot(0,
       type = 'n', # do not plot anything
       xlim = c(-m,m), ylim = c(-m,m),
       axes = F, xlab = '', ylab = '', ...)
  a <- pi/2 - 2*pi/200*0:200
  polygon( cos(a), sin(a) )
  v <- .02
  a <- pi/2 - 2*pi/n*0:n
  segments( (1+v)*cos(a), (1+v)*sin(a),
            (1-v)*cos(a), (1-v)*sin(a) )
  segments( cos(a), sin(a),
            0, 0,
            col = 'light grey', lty = 3)
  ca <- -2*pi/n*(0:50)/50
  for (i in 1:n) {
    a <- pi/2 - 2*pi/n*(i-1)
    b <- pi/2 - 2*pi/n*i
    polygon( c(0, x[i]*cos(a+ca), 0),
             c(0, x[i]*sin(a+ca), 0),
             col=col[i] )
    v <- .1
    text((1+v)*cos(a), (1+v)*sin(a), names(x)[i])
  }
}
clock.plot(x,
  main = "Number of visitors to a web site for each hour of the day")

dev.off()


## 1. Introduction ##

library(readr)
houses  <-  read_tsv('AmesHousing_1.txt')

scale_land  <-  'ordinal'
scale_roof  <-  'nominal'
kitchen_variable  <-  'discrete'

## 2. The Mode for Ordinal Variables ##

library(dplyr)

compute_mode <- function(vector) {
    counts_df  <-  tibble(vector) %>%
        group_by(vector) %>%
        summarise(frequency=n()) %>%
        arrange(desc(frequency))

    counts_df$vector[1]
}

computed_mode  <-  compute_mode(houses$`Land Slope`)

## 3. The Mode for Nominal Variables ##

# The function we wrote (you can copy-paste yours from the previous screen)
library(dplyr)

compute_mode <- function(vector) {
    counts_df  <-  tibble(vector) %>%
        group_by(vector) %>%
        summarise(frequency = n()) %>%
        arrange(desc(frequency))

    counts_df$vector[1]
}
compute_mode_table <- function(vector) {
    counts_df  <-  tibble(vector) %>%
        group_by(vector) %>%
        summarise(frequency = n()) %>%
        arrange(desc(frequency))

    list('mode' = counts_df$vector[1], 'values' = counts_df$frequency)
}

mode <- compute_mode_table(houses$`Roof Style`)$mode
value_counts  <-  compute_mode_table(houses$`Roof Style`)$values

## 4. The Mode for Discrete Variables ##

library(dplyr)

compute_mode <- function(vector) {
    counts_df  <-  tibble(vector) %>%
        group_by(vector) %>%
        summarise(frequency = n()) %>%
        arrange(desc(frequency))

    counts_df$vector[1]
}
bedroom_variable  <-  'discrete'
bedroom_mode  <-  compute_mode(houses$`Bedroom AbvGr`)

price_variable  <-  'continuous'
price_mode <- compute_mode(houses$SalePrice)

## 5. Special Cases ##

library(dplyr)

houses %>%
    mutate(intervals_group = cut(SalePrice,
                                 breaks = seq(0,800000,100000))) %>%
    group_by(intervals_group) %>%
    summarize(frequency = n())
mode  <-  150000
mean  <-  mean(houses$SalePrice)
median  <-  median(houses$SalePrice)

sentence_1  <-  TRUE
sentence_2  <-  TRUE

## 6. Skewed Distributions ##

distribution_1  <-  c('mean' = 3021 , 'median' = 3001, 'mode' = 2947)
distribution_2  <-  c('median' = 924 , 'mode' = 832, 'mean' = 962)
distribution_3  <-  c('mode' =  202, 'mean' =  143, 'median' = 199)
shape_1  <-  'right skew'
shape_2  <-  'right skew'
shape_3  <-  'left skew'

## 7. Challenge: Symmetrical Distributions ##

library(dplyr)

compute_mode <- function(vector) {
    counts_df  <-  tibble(vector) %>%
        group_by(vector) %>%
        summarise(frequency = n()) %>%
        arrange(desc(frequency))

    counts_df$vector[1]
}
library(ggplot2)

ggplot(data = houses,
    aes(x = `Mo Sold`)) +
    geom_density(alpha = 0.1,
                 color='blue',
                 fill='blue') +
    geom_vline(aes(xintercept = compute_mode(`Mo Sold`),
                   color = 'Mode'),
               size = 1.2 ) +
    geom_vline(aes(xintercept = median(`Mo Sold`),
                   color = 'Median'),
               size = 1.2 ) +
    geom_vline(aes(xintercept = mean(`Mo Sold`),
                   color = 'Mean'),
               size = 1.2 ) +
    scale_y_continuous(labels = scales::comma) +
    xlim(1,12)+
    scale_colour_manual(values = c("Mode" = "green",
                                   "Median" = "black",
                                   "Mean" = "orange"),
                        name = "") +
    theme_bw() +
    theme(legend.position='top') +
    xlab("Mo Sold") +
    ylab("Density")

Data Analyst in R/Step 5 - Probability and Statistics/2. Statistics Intermediate in R Averages and Variability/3. The Mode.r


anscombe.sum <- function(df){
results <- as.list(new.env()); # create a list to return with data
results$n <- length(df$x) # sample size
results$x.mean <- mean(df$x) # mean of x
results$y.mean <- mean(df$y) # mean of y
lm.xy <- lm(y ~ x, data=df) # fit slr
results$eq.reg <- lm.xy$coefficients # regression coefficients
results$b1.se <- summary(lm.xy)$coefficients[2,2] # SE of slope
results$b1.t <- summary(lm.xy)$coefficients[2,3] # t-stat of slope
results$x.SS <- sum((df$x-results$x.mean)^2) # x sum of squares
results$ResSS <- sum(lm.xy$residuals^2) # residual SS of y
results$RegSS <- sum((df$y-results$y.mean)^2)-results$ResSS # reg SS
results$xy.cor <- cor(df$x, df$y) # correlation
results$xy.r2 <- summary(lm.xy)$r.squared # R^2 for regression
return(results)
}
# calculate and store summaries by data group g
results.temp <- by(anscombe.long, anscombe.long$g, anscombe.sum)
# make a table
x.table <- cbind( t(t(unlist(results.temp[[1]])))
, t(t(unlist(results.temp[[2]])))
, t(t(unlist(results.temp[[3]])))
, t(t(unlist(results.temp[[4]])))
, t(t(unlist(results.temp[[5]])))
, t(t(unlist(results.temp[[6]])))
, t(t(unlist(results.temp[[7]])))
, t(t(unlist(results.temp[[8]])))
, t(t(unlist(results.temp[[9]])))
, t(t(unlist(results.temp[[10]])))
, t(t(unlist(results.temp[[11]])))
, t(t(unlist(results.temp[[12]])))
, t(t(unlist(results.temp[[13]])))
, t(t(unlist(results.temp[[14]])))
, t(t(unlist(results.temp[[15]])))
, t(t(unlist(results.temp[[16]])))
, t(t(unlist(results.temp[[17]])))
, t(t(unlist(results.temp[[18]])))
, t(t(unlist(results.temp[[19]])))
, t(t(unlist(results.temp[[20]])))
, t(t(unlist(results.temp[[21]])))
, t(t(unlist(results.temp[[22]])))
, t(t(unlist(results.temp[[23]])))
, t(t(unlist(results.temp[[24]])))
, t(t(unlist(results.temp[[25]])))
)
colnames(x.table) <- 1:4 # label the table columns


heart <- read.table("http://stat.ethz.ch/Teaching/Datasets/heart.dat", header = TRUE)

neg.ll <- function(beta, data) {
    llh = 0
    for (i in 1:nrow(data)) {
        g = beta[1] + beta[2] * data$age[i]
        llh = llh + log(choose(data$m[i], data$N[i])) + data$N[i] * g - data$m[i] * log(1 + exp(g))
    }
    -llh
}

beta0.grid <- seq(-10, 10, length = 101)
beta1.grid <- seq(-1, 1, length = 101)

neg.ll.values <- matrix(nrow = 101, ncol = 101)

for (b0 in 1:101) {
    for (b1 in 1:101) {
        neg.ll.values[b0, b1] <- neg.ll(c(beta0.grid[b0], beta1.grid[b1]), heart)
    }
}

contour(beta0.grid, beta1.grid, neg.ll.values, nlevels = 10)

fit <- glm(cbind(N, m - N) ~ age, family = binomial, data = heart)

print(fit)

print(optim(c(0, 0), neg.ll, data = heart))

predict(fit, newdata = data.frame(age = 20:69), type = "response")


##### 1. Electricity
### Obj : 빌딩의 전력량 예측하는 모델
### Data : Electric
### Hypothesis : surface_area를 input으로 쓰면 electricity를 예측하는데 도움이 될 것이다.
### feature : surface_area(Input), electricity(Output)
### Process : Data Load -> EDA -> Modeling -> Test

##### Data Load
Elec <- read.csv('/Users/mac/Downloads/dev/study/R_ML/Class 1/Data/Electric.csv')

##### EDA ... Data Structure & Plot
str(Elec)
plot(Elec$surface_area, Elec$electricity, cex = 3, pch = 19)

##### 난수 발생 알고리즘 초기값 고정 ... Training 할 때마다 샘플이 동일한 기준에서 돌아가야 하니까
set.seed(3)

##### Training Set을 전체 데이터의 70% 지정 (Training Data)
train <- sample(1:nrow(Elec), 0.7 * nrow(Elec))

##### 실제 전력량 (Output, Answer)
real_electricity <- Elec$electricity[-train]

##### Model_1 ... 전력량과 면적의 1차 함수
Model_1 <- lm(electricity ~ surface_area, data = Elec[train, ])
predicted_electricity_1 <- predict(Model_1, Elec[-train, ])
test_error_1 <- mean((real_electricity - predicted_electricity_1)^2)

##### Model_5 ... 전력량과 면적의 5차 함수
Model_5 <- lm(electricity ~ poly(surface_area, 5), data = Elec[train, ])
predicted_electricity_5 <- predict(Model_5, Elec[-train, ])
test_error_5 <- mean((real_electricity - predicted_electricity_5)^2)

##### Model_10 ... 전력량과 면적의 10차 함수
Model_10 <- lm(electricity ~ poly(surface_area, 10), data = Elec[train, ])
predicted_electricity_10 <- predict(Model_10, Elec[-train, ])
test_error_10 <- mean((real_electricity - predicted_electricity_10)^2)

##### 각각의 Error(Cost) 값
test_error_1
test_error_5
test_error_10

## EDA ... 구현한 모든 모델 시각화
plot(Elec$surface_area, Elec$electricity, cex = 3, pch = 15)
a <- seq(500, 820, length = 1000) # surface_area의 값 범위(500~820)를 1000등분 함

points(a, predict(Model_1, data.frame(surface_area = a)), type = 'l', lwd = 10, col = 1)
points(a, predict(Model_5, data.frame(surface_area = a)), type = 'l', lwd = 10, col = 5)
points(a, predict(Model_10, data.frame(surface_area = a)), type = 'l', lwd = 3, col = 10)

##### 2. Cars
### obj : 자동차의 연비를 예측하는 모델
### Data : Cars.csv
### Hypothesis : weight를 Input으로 쓰면 mpg를 예측하는데 도움이 될 것이다.
### Feature : weight(Input), mpg(Output)
### Process : Data Load -> EDA -> Modeling(Train) -> (Validation) -> Test -> Visualization

##### Data Load
Cars <- read.csv("/Users/mac/Downloads/dev/study/R_ML/Class 1/Data/Cars.csv")

##### Data Structure
str(Cars)

##### 데이터 샘플링 초기값 설정
set.seed(1)

##### Training Set을 전체 데이터의 60%로 지정
train <- sample(1:nrow(Cars), 0.6 * nrow(Cars))
##### Validatiaon Set을 전체 데이터의 20%로 지정
validation <- sample(setdiff(1:nrow(Cars), train), 0.2 * nrow(Cars)) # setdiff = 뺸 나머지, 1:768의 vector 주머니에서 train을 빼라
##### Test Set을 전체 데이터의 20%로 지정
test <- setdiff(1:nrow(Cars), c(train, validation))

##### Model_1 : weight(무게)와 mpg(연비) 1차 함수
Model_1 <- lm(mpg ~ weight, data = Cars[train, ])
pred_weight_1 <- predict(Model_1, Cars[validation, ])
validation_error_1 <- mean((Cars$mpg[validation] - pred_weight_1)^2)

##### Model_2 : weight(무게)와 mpg(연비) 10차 함수
Model_2 <- lm(mpg ~ poly(weight, 10), data = Cars[train, ])
pred_weight_2 <- predict(Model_2, Cars[validation, ])
validation_error_2 <- mean((Cars$mpg[validation] - pred_weight_2)^2)

##### Model_3 : weight + horsepower
Model_3 <- lm(mpg ~ weight + horsepower, data = Cars[train, ])
pred_weight_3 <- predict(Model_3, Cars[validation, ])
validation_error_3 <- mean((Cars$mpg[validation] - pred_weight_3)^2)

plot(Cars$weight, Cars$mpg, cex = 3, pch = 15)

##### Machine Learning System Design
### 일반적으로 이 과정을 수십, 수백, 수천 번 반복한다.
### 이 실험의 과정이 한 달이 걸리고, 한 달이 지났을 때,
### Validation Error가 제일 낮아지는 모형을 선택했다.
### 이제 Model에 대한 Test Error를 한 번 딱 측정하고 끝낸다.

##### K-Fold로 나눴다면, 실험이 끝날 때까지 가지고 가야 한다.
##### Cross Validation은 독립적이라서 병렬처리할 수 있다.
# 구조화된 데이터 ... Random Forest, Boost, Decision Tree (~14년 Random Forest, 그 이후에는 Boost 계열이 많이 활용)
# 비구조화된 데이터(이미지, 음성, 텍스트 데이터) ... Deep Learning


hist_nwj <- function(x, alpha=0.01, pvalue=0.99, breaks=NULL, suppress='no') {
    ## plot histogram and normal, Weibull, and Johnson distributions
    ## add lines for upper tolerance limits for given alpha and pvalue
    ## alpha  = 1 - confidence
    ## pvalue = coverage (tolerance interval only)

    ## install.packages('tolerance')
    library(tolerance)
    ## install.packages('SuppDists')
    library(SuppDists)

    ## normal distribution calculations
    tol_out_norm <- normtol.int(x, alpha = alpha, P=pvalue, side=1)
    upper_tolerance_limit_norm <- tol_out_norm$'1-sided.upper'

    ## Weibull distribution calculations
    if (min(x) < 0) {
        cat('\n')
        cat('#####################################################################\n')
        cat('Skip Weibull: Negative values cannot be fit with Weibull distribution\n')
        cat('              Some day I should add logic to skip if that is the case\n')
        cat('#####################################################################\n')
    } else {
        tol_out_weib <-  exttol.int(x, alpha=alpha, P=pvalue, side=1, dist="Weibull")
        shape   <- tol_out_weib$'shape.1'
        scale   <- tol_out_weib$'shape.2'
        upper_tolerance_limit_weib <- tol_out_weib$'1-sided.upper'
    }

    ## Johnson distribution calculations
    tol_out_john <- johnson_tol(x, alpha=alpha, P=pvalue, side=1)
    jparms   <- tol_out_john$jparms
    if (jparms$type == 'SB') {
        upper_tolerance_limit_john <- NA
    } else {
        upper_tolerance_limit_john <- tol_out_john$xtol_upper$`root approximation`
    }

    ## create vectors with density distributions
    xmin    <- min(x)
    xmax    <- max(x,
                   upper_tolerance_limit_norm,
                   upper_tolerance_limit_weib,
                   upper_tolerance_limit_john,
                   na.rm = TRUE)
    chuncks <- (xmax-xmin)/1000
    xrange  <- seq(xmin,xmax,by=chuncks)
    xmean   <- mean(x)
    xsd     <- sd(x)
    xdensity_norm <- dnorm(xrange,xmean,xsd)
    xdensity_weib <- dweibull(xrange,shape=shape,scale=scale)
    xdensity_john <- dJohnson(xrange, jparms)
    maxdensity <- max(xdensity_norm, xdensity_weib, xdensity_john, na.rm=TRUE)

    ## make histogram
    ## warning: xlim range can mess up x-axis
    ## obtain histogram parameters but suppress plot
    out <- hist(x, plot=FALSE)
    if (is.null(breaks)) breaks <- length(out$breaks)
    ymax <- max(out$density, maxdensity)
    ## create plot
    hist(x, breaks=breaks,
         xlim=c(xmin,xmax+(xmax-xmin)/breaks),
         ylim=c(0,maxdensity),
         freq=FALSE)

    ## add distributions
    lines(x=xrange, y=xdensity_norm, col='red',   lty=1)
    lines(x=xrange, y=xdensity_weib, col='blue',  lty=1)
    lines(x=xrange, y=xdensity_john, col='black', lty=1)

    ## add lines for mean and upper 1-sided 99/99 tolerance limits
    abline(v=xmean,col="red")
    abline(v=upper_tolerance_limit_norm,col="red",  lty=2)
    abline(v=upper_tolerance_limit_weib,col="blue", lty=2)
    abline(v=upper_tolerance_limit_john,col="black",lty=2)

    ## print to screen
    if (suppress == 'no') {
        cat("Tolerance limit input parameters:\n")
        cat("   upper, 1-sided,", pvalue*100,"/",(1-alpha)*100,"\n")
        cat("\n")
        cat("Normal distribution (red):\n")
        cat("   mean               =",xmean,"\n")
        cat("   standard deviation =",xsd,"\n")
        cat("   tolerance limit    =",upper_tolerance_limit_norm,"\n")
        cat("\n")
        cat("Weibull distribution (blue):\n")
        cat("   shape              =",shape,"\n")
        cat("   scale              =",scale,"\n")
        cat("   tolerance limit    =",upper_tolerance_limit_weib,"\n")
        cat("\n")
        cat("Johnson distribution (black):\n")
        cat("   gamma              =",jparms$gamma ,"\n")
        cat("   delta              =",jparms$delta ,"\n")
        cat("   xi                 =",jparms$xi    ,"\n")
        cat("   lambda             =",jparms$lambda,"\n")
        cat("   type               =",jparms$type  ,"\n")
        cat("   tolerance limit    =",upper_tolerance_limit_john,"\n")
    }

    return(list(tol_out_norm=tol_out_norm,
                tol_out_weib=tol_out_weib,
                tol_out_john=tol_out_john))

}
## out   <- hist_nwj(mtcars$mpg)
## gamma <- out$tol_out_john$jparms$gamma


> x
[1] 3 6 8
> y
[1] 2 9 0
> x + y
[1]  5 15  8
> x + 1    # 1 is recycled to (1,1,1)
[1] 4 7 9
> x + c(1,4)    # (1,4) is recycled to (1,4,1) but warning issued
[1]  4 10  9
Warning message:
In x + c(1, 4) :
longer object length is not a multiple of shorter object length


beta <- c(9.9029, -3.3733,  4.3080,  1.2049, -0.4126,  0.4739, -0.0366)

startDate <- as.Date("2020-3-2")

logistic <- function (x) 1 / (1 + exp(-x))
logit <- function (x) log(x / (1 - x))

pred <- function (case_ir, death_r, log_gdp_ppp, date, pop) {
  death_r <- death_r + 1e-5
  logistic(beta[1] +
           beta[2]*logit(case_ir) + beta[3]*logit(death_r) +
           (beta[4] + beta[5]*logit(case_ir) + beta[6]*logit(death_r)) * log_gdp_ppp +
           beta[7] * date/30)
}

prediction_df <- read.csv("source-data/cases_deaths_gdp.csv")
prediction_df$date <- as.Date(prediction_df$date)
prediction_df <- prediction_df[order(prediction_df$date), ]

prediction_df$day <- as.integer(prediction_df$date - startDate)

library(runner)
make_average <- function(x, n){
  temp <- x
  for(i in 1:length(x)){
    x[i] <- mean(temp[max(c(1, i-n)):min(c(length(x), i+n))], na.rm = T)
  }
  x
}

prediction_df$pred_ir <- pred(prediction_df$case_ir, prediction_df$death_r, prediction_df$log_gdp_ppp, prediction_df$day, prediction_df$population)

prediction_df$pred_ir_low <- qbinom(0.05, 1000, prediction_df$pred_ir)/1000
prediction_df$pred_ir_high <- qbinom(0.95, 1000, prediction_df$pred_ir)/1000

# prediction_df$pred_ir <- ave(prediction_df$pred_ir, prediction_df$iso3c, FUN = function(x) max_run(make_average(x, n = 5)))
# prediction_df$pred_ir_low <- ave(prediction_df$pred_ir_low, prediction_df$iso3c, FUN = function(x) max_run(make_average(x, n = 5)))
# prediction_df$pred_ir_high <- ave(prediction_df$pred_ir_high, prediction_df$iso3c, FUN = function(x) max_run(make_average(x, n = 5)))

# From predicted sero-prevalence rates, we extract implied case counts
prediction_df$pred_cases <- prediction_df$pred_ir*prediction_df$population
prediction_df$pred_cases_low <- prediction_df$pred_ir_low*prediction_df$population
prediction_df$pred_cases_high <- prediction_df$pred_ir_high*prediction_df$population

# The following five lines creates world totals:
prediction_df$world_cases <- ave(prediction_df$cases, prediction_df$date, FUN = sum)
prediction_df$pred_world_cases <- ave(prediction_df$pred_cases, prediction_df$date, FUN = sum)
prediction_df$pred_world_cases_low <- ave(prediction_df$pred_cases_low, prediction_df$date, FUN = sum)
prediction_df$pred_world_cases_high <- ave(prediction_df$pred_cases_high, prediction_df$date, FUN = sum)

# This re-produces our inset plot:
library(ggplot2)
ggplot(prediction_df[!duplicated(prediction_df$date), ],
       aes(x=as.Date(date), ymin = 0))+geom_ribbon(aes(ymax=pred_world_cases, fill = "Probably Infected, World"))+
  theme_minimal()+geom_ribbon(aes(ymin = 0, ymax = world_cases, fill = "Reported Cases, World"))+
  # geom_line(aes(y=pred_world_cases_low), col = "white")+
  # geom_line(aes(y=pred_world_cases_high), col = "black")+
  scale_y_continuous(labels = scales::comma)+
  theme(legend.title = element_blank(), legend.position = "bottom")+xlab("")+ylab("")

latest <- prediction_df[prediction_df$date == max(prediction_df$date),]

# ggplot(latest, aes(x=country,y=pred_ir)) + geom_bar(stat="identity")

# To generate the large plot, we first-differences and by continent and a select few large countries:

# These lines define our groups (colors in the large plot)
prediction_df$continents_plus <- prediction_df$continent
prediction_df$continents_plus[prediction_df$country == "United States"] <- "United States"
prediction_df$continents_plus[prediction_df$country == "China"] <- "China"
prediction_df$continents_plus[prediction_df$country == "India"] <- "India"
prediction_df$continents_plus[prediction_df$country == "Brazil"] <- "Brazil"

new_cases_fun <- function(x) {
  x <- x - c(0, x)[1:length(x)]
  # x <- make_average(x, n = 10)
  x }

# This function takes first differences by country and sums countries together by day and group:
big_chart_data <- function(prediction_df, grouping = "continent_plus"){

  prediction_df$region <- prediction_df[, grouping]

  regions <- prediction_df

  regions$region_cases <- ave(regions$cases, paste0(regions$date, "_", regions$region), FUN = sum)
  regions$pred_region_cases <- ave(regions$pred_cases, paste0(regions$date, "_", regions$region), FUN = sum)
  regions$pred_region_cases_low <- ave(regions$pred_cases_low, paste0(regions$date, "_", regions$region), FUN = sum)
  regions$pred_region_cases_high <- ave(regions$pred_cases_high, paste0(regions$date, "_", regions$region), FUN = sum)

  new_cases_fun <- function(x) {
    x <- x - c(0, x)[1:length(x)]
    x <- make_average(x, n = 7)
    x <- make_average(x, n = 7)
    x }
  regions <- regions[!duplicated(paste0(regions$date, "_", regions$region)), ]

  # regions$pred_region_cases <- ave(regions$pred_region_cases, regions$region, FUN = function(x) make_average(x, n = 10))
  # regions$pred_region_cases_low <- ave(regions$pred_region_cases_low, regions$region, FUN = function(x) make_average(x, n = 10))
  # regions$pred_region_cases_high <- ave(regions$pred_region_cases_high, regions$region, FUN = function(x) make_average(x, n = 10))

  regions$new_cases <- ave(regions$region_cases, regions$region, FUN = new_cases_fun)
  regions$new_pred_cases <- ave(regions$pred_region_cases, regions$region, FUN = new_cases_fun)
  regions$new_pred_cases_high <- ave(regions$pred_region_cases_high, regions$region, FUN = new_cases_fun)
  regions$new_pred_cases_low <- ave(regions$pred_region_cases_low, regions$region, FUN = new_cases_fun)
  return(regions)}
continents_plus <- big_chart_data(prediction_df, grouping = "continents_plus") # This runs the above function

# This reproduces our first large plot:
ggplot(continents_plus,
       aes(x=date, ymin = 0))+geom_area(aes(y=new_pred_cases, fill = continents_plus), col = "white")+
  theme_minimal()+
  #  geom_line(aes(y=new_pred_cases_high), col = "white")+
  # geom_line(aes(y=new_pred_cases_low), col = "black")+
  scale_y_continuous(labels = scales::comma)+ylab("")+
  theme(legend.title = element_blank(), legend.position = "bottom")+xlab("")


# Goal: Standard computations with well-studied distributions.

# The normal distribution is named "norm". With this, we have:

# Normal density
dnorm(c(-1.96,0,1.96))

# Cumulative normal density
pnorm(c(-1.96,0,1.96))

# Inverse of this
qnorm(c(0.025,.5,.975))
pnorm(qnorm(c(0.025,.5,.975)))

# 1000 random numbers from the normal distribution
summary(rnorm(1000))

# Here's the same ideas, for the chi-squared distribution with 10 degrees
# of freedom.
dchisq(c(0,5,10), df=10)

# Cumulative normal density
pchisq(c(0,5,10), df=10)

# Inverse of this
qchisq(c(0.025,.5,.975), df=10)

# 1000 random numbers from the normal distribution
summary(rchisq(1000, df=10))

RFrontEndSolution/Tests Repo/Rscripts All (163 files)/p9.r


# Example : 1   Chapter : 6.3     Page No: 313
# Solve Differential equation

# lambda1,lamda2,x1,x2,c,d are computed here.. for remaining details look textbook
A<-matrix(c(0,1,1,0),ncol=2)
lambda<-eigen(A)$values
x<-eigen(A)$vectors #These are normalised eigen vectors
#to get eigen vectors in textbook .. Multiply them with the scalars
x[,1]<-x[,1]*(1/x[1,1])
x[,2]<-x[,2]*(1/x[1,2])
print(x)
u<-c(4,2)
cd<-solve(x,u)
C<-cd[1]
D<-cd[2]
print("Lambda 1 and Lambda 2")
print(lambda)
print("x1 and x2")
print(x)
print("C and D are")
print(C)
print(D)


#' crib_fun
#' converts a vector of [0,1] values to (0,1) a la Cribari-Neto & Zeileis 2010
#' @param x a vector of values on the interval [0,1]
#' @param N alternative sample size. This is useful when tranforming a matrix in the dirchlet case, rather than just a vector as in the beta case.
#'
#' @return  a vector of values on the interval (0,1)
#' @export
#'
#' @examples
crib_fun <- function(x,N = NA){
  #default use length of vector.
  if( is.na(N)){
    out <- (x * (length(x) - 1) + 0.5) / length(x)
  }
  #custom- useful when I am in multivariate case.
  if(!is.na(N)){
    out <- (x * (N - 1) + 0.5) / N
  }
  return(out)
}


#
# Example R program
#

# example from https://github.com/jyypma/nloptr/blob/master/man/nloptr.Rd

library('nloptr')

## Rosenbrock Banana function and gradient in separate functions
eval_f <- function(x) {
    return( 100 * (x[2] - x[1] * x[1])^2 + (1 - x[1])^2 )
}

eval_grad_f <- function(x) {
    return( c( -400 * x[1] * (x[2] - x[1] * x[1]) - 2 * (1 - x[1]),
                200 * (x[2] - x[1] * x[1])) )
}

# initial values
x0 <- c( -1.2, 1 )

opts <- list("algorithm"="NLOPT_LD_LBFGS",
             "xtol_rel"=1.0e-8)

# solve Rosenbrock Banana function
res <- nloptr( x0=x0,
               eval_f=eval_f,
               eval_grad_f=eval_grad_f,
               opts=opts)
print( res )

## Rosenbrock Banana function and gradient in one function
# this can be used to economize on calculations
eval_f_list <- function(x) {
    return( list( "objective" = 100 * (x[2] - x[1] * x[1])^2 + (1 - x[1])^2,
                  "gradient"  = c( -400 * x[1] * (x[2] - x[1] * x[1]) - 2 * (1 - x[1]),
                                    200 * (x[2] - x[1] * x[1])) ) )
}

# solve Rosenbrock Banana function using an objective function that
# returns a list with the objective value and its gradient
res <- nloptr( x0=x0,
               eval_f=eval_f_list,
               opts=opts)
print( res )

# Example showing how to solve the problem from the NLopt tutorial.
#
# min sqrt( x2 )
# s.t. x2 >= 0
#      x2 >= ( a1*x1 + b1 )^3
#      x2 >= ( a2*x1 + b2 )^3
# where
# a1 = 2, b1 = 0, a2 = -1, b2 = 1
#
# re-formulate constraints to be of form g(x) <= 0
#      ( a1*x1 + b1 )^3 - x2 <= 0
#      ( a2*x1 + b2 )^3 - x2 <= 0

library('nloptr')

# objective function
eval_f0 <- function( x, a, b ){
    return( sqrt(x[2]) )
}

# constraint function
eval_g0 <- function( x, a, b ) {
    return( (a*x[1] + b)^3 - x[2] )
}

# gradient of objective function
eval_grad_f0 <- function( x, a, b ){
    return( c( 0, .5/sqrt(x[2]) ) )
}

# jacobian of constraint
eval_jac_g0 <- function( x, a, b ) {
    return( rbind( c( 3*a[1]*(a[1]*x[1] + b[1])^2, -1.0 ),
                   c( 3*a[2]*(a[2]*x[1] + b[2])^2, -1.0 ) ) )
}

# functions with gradients in objective and constraint function
# this can be useful if the same calculations are needed for
# the function value and the gradient
eval_f1 <- function( x, a, b ){
    return( list("objective"=sqrt(x[2]),
                 "gradient"=c(0,.5/sqrt(x[2])) ) )
}

eval_g1 <- function( x, a, b ) {
    return( list( "constraints"=(a*x[1] + b)^3 - x[2],
                  "jacobian"=rbind( c( 3*a[1]*(a[1]*x[1] + b[1])^2, -1.0 ),
                                    c( 3*a[2]*(a[2]*x[1] + b[2])^2, -1.0 ) ) ) )
}

# define parameters
a <- c(2,-1)
b <- c(0, 1)

# Solve using NLOPT_LD_MMA with gradient information supplied in separate function
res0 <- nloptr( x0=c(1.234,5.678),
                eval_f=eval_f0,
                eval_grad_f=eval_grad_f0,
                lb = c(-Inf,0),
                ub = c(Inf,Inf),
                eval_g_ineq = eval_g0,
                eval_jac_g_ineq = eval_jac_g0,
                opts = list("algorithm"="NLOPT_LD_MMA"),
                a = a,
                b = b )
print( res0 )

# Solve using NLOPT_LN_COBYLA without gradient information
res1 <- nloptr( x0=c(1.234,5.678),
                eval_f=eval_f0,
                lb = c(-Inf,0),
                ub = c(Inf,Inf),
                eval_g_ineq = eval_g0,
                opts = list("algorithm"="NLOPT_LN_COBYLA"),
                a = a,
                b = b )
print( res1 )

# Solve using NLOPT_LD_MMA with gradient information in objective function
res2 <- nloptr( x0=c(1.234,5.678),
                eval_f=eval_f1,
                lb = c(-Inf,0),
                ub = c(Inf,Inf),
                eval_g_ineq = eval_g1,
                opts = list("algorithm"="NLOPT_LD_MMA", "check_derivatives"=TRUE),
                a = a,
                b = b )
print( res2 )


#  confidence interval for the ratio of the two variances

y1bar=38.48
s1=16.37
n1=40
y2bar=26.93
s2=9.88
n2=40
alpha=0.05
FU=qf(1-alpha/2,39,39)
FL=1/FU

# confidence interval for sigma1^2/sigma2^2
left_i=(s1^2/s2^2)*FL
right_i=(s1^2/s2^2)*FU
print(left_i)
print(right_i)


#' Expected number of ENC given GC3 content
#'
#' Calculates the expected ENC based on Wright's formula given GC3 percentage
#' @param gc3 a number of GC3 content
#' @return a number of the expected ENC given the GC3 content
#'
#' @export

enc_exp <- function(gc3=0){
  return(2+gc3+29/(gc3^2+(1-gc3)^2))
}