diff --git a/shiny/densityKernel/DESCRIPTION b/shiny/densityKernel/DESCRIPTION new file mode 100644 index 0000000000000000000000000000000000000000..f6e92c461f806647311cd820dc0d58586b0a09bb --- /dev/null +++ b/shiny/densityKernel/DESCRIPTION @@ -0,0 +1,7 @@ +Title: Explorando interfaces gráficas interativas no R - 2 +Author: Eduardo E. Ribeiro Jr e Walmes M. Zeviani +AuthorUrl: https://gitlab.c3sl.ufpr.br/pet-estatistica/iguir2 +License: GPL-3 +DisplayMode: Showcase +Tags: iguir2 +Type: Shiny diff --git a/shiny/densityKernel/densityKelnel.Rproj b/shiny/densityKernel/densityKelnel.Rproj new file mode 100644 index 0000000000000000000000000000000000000000..3715d52d2dcf3d8d8b4e5796956246ae2729f2c2 --- /dev/null +++ b/shiny/densityKernel/densityKelnel.Rproj @@ -0,0 +1,13 @@ +Version: 1.0 + +RestoreWorkspace: Default +SaveWorkspace: Default +AlwaysSaveHistory: Default + +EnableCodeIndexing: Yes +UseSpacesForTab: Yes +NumSpacesForTab: 4 +Encoding: UTF-8 + +RnwWeave: knitr +LaTeX: pdfLaTeX diff --git a/shiny/densityKernel/server.R b/shiny/densityKernel/server.R new file mode 100644 index 0000000000000000000000000000000000000000..ad065a61f5f4472c800c3a7d9ba830867088895c --- /dev/null +++ b/shiny/densityKernel/server.R @@ -0,0 +1,30 @@ +library(shiny) + +shinyServer( + function(input, output) { + output$PLOT_DENSITY <- renderPlot({ + ## Estimação da densidade. + aux <- density(precip, + width=input$WIDTH, + kernel=input$KERNEL) + plot(aux, main=NA, col=input$CURVE_COLOR) + ## Indica a banda. + arrows(input$CENTER-0.5*input$WIDTH, 0, + input$CENTER+0.5*input$WIDTH, 0, + length=0.1, code=3, angle=90, col=2) + ## Exibe o ponto sobre a função densidade. + y0 <- approx(aux$x, aux$y, xout=input$CENTER) + arrows(input$CENTER, 0, + input$CENTER, y0$y, + length=0.1, col=2) + ## Representa a função kernel para 1 observação. + d <- density(input$CENTER, + width=input$WIDTH, + kernel=input$KERNEL) + lines(d$x, d$y/length(precip), col=2) + ## Inclui as marcas sobre o eixo. + if (input$DRAW_RUG){ + rug(precip) + } + }) + }) diff --git a/shiny/densityKernel/ui.R b/shiny/densityKernel/ui.R new file mode 100644 index 0000000000000000000000000000000000000000..2b50d187846d96d1928f71270fa004ff43811f0a --- /dev/null +++ b/shiny/densityKernel/ui.R @@ -0,0 +1,31 @@ +library(shiny) + +kernels <- eval(formals(density.default)$kernel) + +shinyUI( + fluidPage( + titlePanel("Gráfico de densidade Kernel"), + sidebarLayout( + sidebarPanel( + radioButtons(inputId="KERNEL", + label="Escolha a função kernel:", + choices=kernels, + selected=sample(x=kernels, size=1)), + checkboxInput(inputId="DRAW_RUG", + label="Colocar o 'rug':", + value=TRUE), + textInput(inputId="CURVE_COLOR", + label="Cor da linha:", + value="black"), + sliderInput(inputId="WIDTH", + label="Largura de banda:", + min=5, max=70, value=10, step=1), + sliderInput(inputId="CENTER", + label="Valor de referência:", + min=7, max=67, value=30, step=1) + ), + mainPanel( + plotOutput("PLOT_DENSITY") + ) + ) + )) diff --git a/shiny/downUpFiles/DESCRIPTION b/shiny/downUpFiles/DESCRIPTION new file mode 100644 index 0000000000000000000000000000000000000000..f6e92c461f806647311cd820dc0d58586b0a09bb --- /dev/null +++ b/shiny/downUpFiles/DESCRIPTION @@ -0,0 +1,7 @@ +Title: Explorando interfaces gráficas interativas no R - 2 +Author: Eduardo E. Ribeiro Jr e Walmes M. Zeviani +AuthorUrl: https://gitlab.c3sl.ufpr.br/pet-estatistica/iguir2 +License: GPL-3 +DisplayMode: Showcase +Tags: iguir2 +Type: Shiny diff --git a/shiny/downUpFiles/downUpFiles.Rproj b/shiny/downUpFiles/downUpFiles.Rproj new file mode 100644 index 0000000000000000000000000000000000000000..3715d52d2dcf3d8d8b4e5796956246ae2729f2c2 --- /dev/null +++ b/shiny/downUpFiles/downUpFiles.Rproj @@ -0,0 +1,13 @@ +Version: 1.0 + +RestoreWorkspace: Default +SaveWorkspace: Default +AlwaysSaveHistory: Default + +EnableCodeIndexing: Yes +UseSpacesForTab: Yes +NumSpacesForTab: 4 +Encoding: UTF-8 + +RnwWeave: knitr +LaTeX: pdfLaTeX diff --git a/shiny/downUpFiles/server.R b/shiny/downUpFiles/server.R new file mode 100644 index 0000000000000000000000000000000000000000..8ef0c020c8ba64d5da2c603b7171d66a9c273f38 --- /dev/null +++ b/shiny/downUpFiles/server.R @@ -0,0 +1,63 @@ +library(shiny) + +shinyServer(function(input, output, session){ + + FILEURL <- reactive({ + fileUploaded <- input$THEFILE + if (is.null(fileUploaded)){ + return(NULL) + } else { + return(fileUploaded$datapath) + } + }) + + DATASET <- reactive({ + fileurl <- isolate(FILEURL()) + input$RUN + if (is.null(fileurl)){ + return(NULL) + } else { + dados <- read.table(fileurl, + header=input$HEADER, + sep=input$SEPARATOR, + quote=input$QUOTATION, + dec=input$DECIMAL) + return(dados) + } + }) + + observe({ + dados <- DATASET() + if (!is.null(dados)) { + updateSelectInput(session, + inputId="VARIABLE", + choices=names(dados), + selected=names(dados)[1]) + } + }) + + STEM <- reactive({ + dados <- DATASET() + y <- dados[, input$VARIABLE] + if (is.numeric(y)) { + st <- capture.output(stem(y)) + return(st) + } else { + return(NULL) + } + }) + output$STEM <- renderPrint({ + cat(STEM(), sep="\n") + }) + + output$DOWNLOADDATA <- downloadHandler( + filename=function(){ + "stem.txt" + }, + content=function(file){ + cat(STEM(), + sep="\n", file=file) + } + ) + +}) diff --git a/shiny/downUpFiles/ui.R b/shiny/downUpFiles/ui.R new file mode 100644 index 0000000000000000000000000000000000000000..0f73a6a61ccc7a3a510e235d9690114736993458 --- /dev/null +++ b/shiny/downUpFiles/ui.R @@ -0,0 +1,58 @@ +##---------------------------------------------------------------------- +## Upload e Download. + +library(shiny) + +shinyUI(fluidPage( + titlePanel("Uploading Files"), + sidebarLayout( + sidebarPanel( + fileInput(inputId="THEFILE", + label="Selecione o arquivo", + accept=c( + 'text/csv', + 'text/comma-separated-values', + '.csv') + ), + checkboxInput(inputId="AVANCADO", + label="Opções avançadas", + value=FALSE), + conditionalPanel( + "input.AVANCADO", + checkboxInput(inputId="HEADER", + label="Cabeçalho", + value=TRUE), + radioButtons(inputId="SEPARATOR", + label="Separador de campo", + choices=c("Vírgula"=",", + "Ponto e vírgula"=";", + "Tabulação"="\t"), + selected=","), + radioButtons(inputId="DECIMAL", + label="Decimal numérico", + choices=c(Ponto=".", + Vírgula=","), + selected="."), + radioButtons(inputId="QUOTATION", + label="Quote", + choices=c( + Nenhuma="", + Dupla='"', + Simples="'"), + selected='"') + ), + actionButton(inputId="RUN", + label="Processar"), + hr(), + selectInput(inputId="VARIABLE", + label="Variável", + choices="", + selected=""), + downloadButton(outputId="DOWNLOADDATA", + label="Download") + ), + mainPanel( + verbatimTextOutput("STEM") + ) + ) +)) diff --git a/shiny/downloadLista/DESCRIPTION b/shiny/downloadLista/DESCRIPTION new file mode 100644 index 0000000000000000000000000000000000000000..f6e92c461f806647311cd820dc0d58586b0a09bb --- /dev/null +++ b/shiny/downloadLista/DESCRIPTION @@ -0,0 +1,7 @@ +Title: Explorando interfaces gráficas interativas no R - 2 +Author: Eduardo E. Ribeiro Jr e Walmes M. Zeviani +AuthorUrl: https://gitlab.c3sl.ufpr.br/pet-estatistica/iguir2 +License: GPL-3 +DisplayMode: Showcase +Tags: iguir2 +Type: Shiny diff --git a/shiny/downloadLista/comparMultiplasDBC.Rnw b/shiny/downloadLista/comparMultiplasDBC.Rnw new file mode 100644 index 0000000000000000000000000000000000000000..e576e90dc4ab3bb74bc8872b332c22fd69c5abc5 --- /dev/null +++ b/shiny/downloadLista/comparMultiplasDBC.Rnw @@ -0,0 +1,93 @@ +\begin{defproblem}{comparMultDBC_GRR_} + +<<include=FALSE>>= +##------------------------------------------- +## Definições do knitr. + +opts_chunk$set( + cache=FALSE, + tidy=FALSE, + fig.keep="last", + ## fig.show="hide", + echo=FALSE, + message=FALSE, + error=FALSE, + warning=FALSE, + results="hide", + fig.width=5, + fig.height=4, + pointsize=10, + out.width="7cm", + fig.align="center", + ## fig.pos="H", + dev.args=list(pdf=list(family="Palatino")) +) + +##------------------------------------------- +## Geração dos dados. + +set.seed(_GRR_) + +pre <- "http://www.leg.ufpr.br/~walmes/data/" +dbc <- c("pimentel_colesterol.txt", + "pimentel_mandioca.txt", + "pimentel_aradura.txt", + "ramalho_consorcio.txt", + "ramalho_arroz1.txt") +url <- sample(dbc, size=1) + +link <- paste0("http://www.leg.ufpr.br/~walmes/data/", + gsub(x=url, pattern="[_]", replacement="\\\\_")) + +url <- paste0(pre, url) + +pcm <- c("de Duncan", + "t (LSD)", + "t (LSD) com proteção de Bonferroni", + "de Tukey (HSD)", + "de Student-Newman-Keuls (SNK)") +pcm <- sample(pcm, size=1) +alpha <- sample(c(5,10), size=1) + +##------------------------------------------- +## Solução. + +@ + +\noindent Carregue os dados obtidos de um experimento realizado em +delineamento de blocos casualizados. Os dados estão disponíveis pelo +endereço abaixo. Os dados estão em arquivo texto com delimitador de +campos tabulação, separador decimal vírgula e primeira linha sendo o +cabeçalho. Dentro do arquivo as primeiras linhas foram comentadas e +apresentam uma descrição dos dados, como nome das variáveis, +responsáveis ou fonte. + +\begin{center} + \url{\Sexpr{link}} +\end{center} + +\begin{compactenum} + \item Importe os dados e faça uma análise exploratória. + \item Escreva o modelo estatístico justificado pelo delineamento e + suas pressuposições. + \item Ajuste o modelo aos dados e faça uma verificação sobre a + adequação dos pressupostos. Havendo fuga dos pressupostos, tome + medidas para adequá-los. + \item Obtenha o quadro de análise de variância, descreva as hipóteses + que estão sendo avaliadas e interprete os resultados. + \item Aplique o teste de comparações múltiplas \Sexpr{pcm} ao nível + nominal de significância de \Sexpr{alpha}\% e interprete os + resultados. + \item Apresente os resultados em um gráficos de segmentos com o + intervalo de confiança de \Sexpr{100-alpha}\% para a média de cada + nível do fator estudado. Dê ao gráfico legendas apropriadas conforme + a descrição contida no arquivo importado. +\end{compactenum} + +\begin{onlysolution} +\begin{solution} + \textcolor{A fazer.} +\end{solution} +\end{onlysolution} + +\end{defproblem} diff --git a/shiny/downloadLista/comparMultiplasDIC.Rnw b/shiny/downloadLista/comparMultiplasDIC.Rnw new file mode 100644 index 0000000000000000000000000000000000000000..c5fe9dee099ac834a4e47ef598512cef4c33b7ea --- /dev/null +++ b/shiny/downloadLista/comparMultiplasDIC.Rnw @@ -0,0 +1,91 @@ +\begin{defproblem}{comparMultDIC_GRR_} + +<<include=FALSE>>= +##------------------------------------------- +## Definições do knitr. + +opts_chunk$set( + cache=FALSE, + tidy=FALSE, + fig.keep="last", + ## fig.show="hide", + echo=FALSE, + message=FALSE, + error=FALSE, + warning=FALSE, + results="hide", + fig.width=5, + fig.height=4, + pointsize=10, + out.width="7cm", + fig.align="center", + ## fig.pos="H", + dev.args=list(pdf=list(family="Palatino")) +) + +##------------------------------------------- +## Geração dos dados. + +set.seed(_GRR_) + +pre <- "http://www.leg.ufpr.br/~walmes/data/" +dic <- c("diasbarros_manga.txt", + "diasbarros_feijao.txt", + "ramalho_absorcao.txt") +url <- sample(dic, size=1) + +link <- paste0("http://www.leg.ufpr.br/~walmes/data/", + gsub(x=url, pattern="[_]", replacement="\\\\_")) + +url <- paste0(pre, url) + +pcm <- c("de Duncan", + "t (LSD)", + "t (LSD) com proteção de Bonferroni", + "de Tukey (HSD)", + "de Student-Newman-Keuls (SNK)") +pcm <- sample(pcm, size=1) +alpha <- sample(c(5,10), size=1) + +##------------------------------------------- +## Solução. + +@ + +\noindent Carregue os dados obtidos de um experimento realizado em +delineamento inteiramente casualizado. Os dados estão disponíveis pelo +endereço abaixo. Os dados estão em arquivo texto com delimitador de +campos tabulação, separador decimal vírgula e primeira linha sendo o +cabeçalho. Dentro do arquivo as primeiras linhas foram comentadas e +apresentam uma descrição dos dados, como nome das variáveis, +responsáveis ou fonte. + +\begin{center} + \url{\Sexpr{link}} +\end{center} + +\begin{compactenum} + \item Importe os dados e faça uma análise exploratória. + \item Escreva o modelo estatístico justificado pelo delineamento e + suas pressuposições. + \item Ajuste o modelo aos dados e faça uma verificação sobre a + adequação dos pressupostos. Havendo fuga dos pressupostos, tome + medidas para adequá-los. + \item Obtenha o quadro de análise de variância, descreva as hipóteses + que estão sendo avaliadas e interprete os resultados. + \item Aplique o teste de comparações múltiplas \Sexpr{pcm} ao nível + nominal de significância de \Sexpr{alpha}\% e interprete os + resultados. + \item Apresente os resultados em um gráficos de segmentos com o + intervalo de confiança de \Sexpr{100-alpha}\% para a média de cada + nível do fator estudado. Dê ao gráfico legendas apropriadas conforme + a descrição contida no arquivo importado. +\end{compactenum} + +\begin{onlysolution} +\begin{solution} + \textcolor{A fazer.} +\end{solution} +\end{onlysolution} + +\end{defproblem} diff --git a/shiny/downloadLista/comparMultiplasDQL.Rnw b/shiny/downloadLista/comparMultiplasDQL.Rnw new file mode 100644 index 0000000000000000000000000000000000000000..56bc32983fae5b5d27448971580baacda28d8002 --- /dev/null +++ b/shiny/downloadLista/comparMultiplasDQL.Rnw @@ -0,0 +1,93 @@ +\begin{defproblem}{comparMultDQL_GRR_} + +<<include=FALSE>>= +##------------------------------------------- +## Definições do knitr. + +opts_chunk$set( + cache=FALSE, + tidy=FALSE, + fig.keep="last", + ## fig.show="hide", + echo=FALSE, + message=FALSE, + error=FALSE, + warning=FALSE, + results="hide", + fig.width=5, + fig.height=4, + pointsize=10, + out.width="7cm", + fig.align="center", + ## fig.pos="H", + dev.args=list(pdf=list(family="Palatino")) +) + +##------------------------------------------- +## Geração dos dados. + +set.seed(_GRR_) + +pre <- "http://www.leg.ufpr.br/~walmes/data/" +dbc <- c("pimentel_canadeacucar2.txt", + "pimentel_crotalaria.txt", + "diasbarros_cacau.txt", + "diasbarros_cafe.txt", + "zimmermann_dql8x8.txt") +url <- sample(dbc, size=1) + +link <- paste0("http://www.leg.ufpr.br/~walmes/data/", + gsub(x=url, pattern="[_]", replacement="\\\\_")) + +url <- paste0(pre, url) + +pcm <- c("de Duncan", + "t (LSD)", + "t (LSD) com proteção de Bonferroni", + "de Tukey (HSD)", + "de Student-Newman-Keuls (SNK)") +pcm <- sample(pcm, size=1) +alpha <- sample(c(5,10), size=1) + +##------------------------------------------- +## Solução. + +@ + +\noindent Carregue os dados obtidos de um experimento realizado em +delineamento de quadrado latino. Os dados estão disponíveis pelo +endereço abaixo. Os dados estão em arquivo texto com delimitador de +campos tabulação, separador decimal vírgula e primeira linha sendo o +cabeçalho. Dentro do arquivo as primeiras linhas foram comentadas e +apresentam uma descrição dos dados, como nome das variáveis, +responsáveis ou fonte. + +\begin{center} + \url{\Sexpr{link}} +\end{center} + +\begin{compactenum} + \item Importe os dados e faça uma análise exploratória. + \item Escreva o modelo estatístico justificado pelo delineamento e + suas pressuposições. + \item Ajuste o modelo aos dados e faça uma verificação sobre a + adequação dos pressupostos. Havendo fuga dos pressupostos, tome + medidas para adequá-los. + \item Obtenha o quadro de análise de variância, descreva as hipóteses + que estão sendo avaliadas e interprete os resultados. + \item Aplique o teste de comparações múltiplas \Sexpr{pcm} ao nível + nominal de significância de \Sexpr{alpha}\% e interprete os + resultados. + \item Apresente os resultados em um gráficos de segmentos com o + intervalo de confiança de \Sexpr{100-alpha}\% para a média de cada + nível do fator estudado. Dê ao gráfico legendas apropriadas conforme + a descrição contida no arquivo importado. +\end{compactenum} + +\begin{onlysolution} +\begin{solution} + \textcolor{A fazer.} +\end{solution} +\end{onlysolution} + +\end{defproblem} diff --git a/shiny/downloadLista/exercGRR.Rnw b/shiny/downloadLista/exercGRR.Rnw new file mode 100644 index 0000000000000000000000000000000000000000..4274c9d954ee2a73579de1a02accb454291ee054 --- /dev/null +++ b/shiny/downloadLista/exercGRR.Rnw @@ -0,0 +1,93 @@ +\begin{defproblem}{comparMultDBC12345678} + +<<include=FALSE>>= +##------------------------------------------- +## Definições do knitr. + +opts_chunk$set( + cache=FALSE, + tidy=FALSE, + fig.keep="last", + ## fig.show="hide", + echo=FALSE, + message=FALSE, + error=FALSE, + warning=FALSE, + results="hide", + fig.width=5, + fig.height=4, + pointsize=10, + out.width="7cm", + fig.align="center", + ## fig.pos="H", + dev.args=list(pdf=list(family="Palatino")) +) + +##------------------------------------------- +## Geração dos dados. + +set.seed(12345678) + +pre <- "http://www.leg.ufpr.br/~walmes/data/" +dbc <- c("pimentel_colesterol.txt", + "pimentel_mandioca.txt", + "pimentel_aradura.txt", + "ramalho_consorcio.txt", + "ramalho_arroz1.txt") +url <- sample(dbc, size=1) + +link <- paste0("http://www.leg.ufpr.br/~walmes/data/", + gsub(x=url, pattern="[_]", replacement="\\\\_")) + +url <- paste0(pre, url) + +pcm <- c("de Duncan", + "t (LSD)", + "t (LSD) com proteção de Bonferroni", + "de Tukey (HSD)", + "de Student-Newman-Keuls (SNK)") +pcm <- sample(pcm, size=1) +alpha <- sample(c(5,10), size=1) + +##------------------------------------------- +## Solução. + +@ + +\noindent Carregue os dados obtidos de um experimento realizado em +delineamento de blocos casualizados. Os dados estão disponíveis pelo +endereço abaixo. Os dados estão em arquivo texto com delimitador de +campos tabulação, separador decimal vírgula e primeira linha sendo o +cabeçalho. Dentro do arquivo as primeiras linhas foram comentadas e +apresentam uma descrição dos dados, como nome das variáveis, +responsáveis ou fonte. + +\begin{center} + \url{\Sexpr{link}} +\end{center} + +\begin{compactenum} + \item Importe os dados e faça uma análise exploratória. + \item Escreva o modelo estatístico justificado pelo delineamento e + suas pressuposições. + \item Ajuste o modelo aos dados e faça uma verificação sobre a + adequação dos pressupostos. Havendo fuga dos pressupostos, tome + medidas para adequá-los. + \item Obtenha o quadro de análise de variância, descreva as hipóteses + que estão sendo avaliadas e interprete os resultados. + \item Aplique o teste de comparações múltiplas \Sexpr{pcm} ao nível + nominal de significância de \Sexpr{alpha}\% e interprete os + resultados. + \item Apresente os resultados em um gráficos de segmentos com o + intervalo de confiança de \Sexpr{100-alpha}\% para a média de cada + nível do fator estudado. Dê ao gráfico legendas apropriadas conforme + a descrição contida no arquivo importado. +\end{compactenum} + +\begin{onlysolution} +\begin{solution} + \textcolor{A fazer.} +\end{solution} +\end{onlysolution} + +\end{defproblem} diff --git a/shiny/downloadLista/exercGRR.tex b/shiny/downloadLista/exercGRR.tex new file mode 100644 index 0000000000000000000000000000000000000000..42991e5a54e95b45b78cae39f4db18ba4682abff --- /dev/null +++ b/shiny/downloadLista/exercGRR.tex @@ -0,0 +1,41 @@ +\begin{defproblem}{comparMultDBC12345678} + + + +\noindent Carregue os dados obtidos de um experimento realizado em +delineamento de blocos casualizados. Os dados estão disponíveis pelo +endereço abaixo. Os dados estão em arquivo texto com delimitador de +campos tabulação, separador decimal vírgula e primeira linha sendo o +cabeçalho. Dentro do arquivo as primeiras linhas foram comentadas e +apresentam uma descrição dos dados, como nome das variáveis, +responsáveis ou fonte. + +\begin{center} + \url{http://www.leg.ufpr.br/~walmes/data/ramalho\_arroz1.txt} +\end{center} + +\begin{compactenum} + \item Importe os dados e faça uma análise exploratória. + \item Escreva o modelo estatístico justificado pelo delineamento e + suas pressuposições. + \item Ajuste o modelo aos dados e faça uma verificação sobre a + adequação dos pressupostos. Havendo fuga dos pressupostos, tome + medidas para adequá-los. + \item Obtenha o quadro de análise de variância, descreva as hipóteses + que estão sendo avaliadas e interprete os resultados. + \item Aplique o teste de comparações múltiplas t (LSD) ao nível + nominal de significância de 10\% e interprete os + resultados. + \item Apresente os resultados em um gráficos de segmentos com o + intervalo de confiança de 90\% para a média de cada + nível do fator estudado. Dê ao gráfico legendas apropriadas conforme + a descrição contida no arquivo importado. +\end{compactenum} + +\begin{onlysolution} +\begin{solution} + \textcolor{A fazer.} +\end{solution} +\end{onlysolution} + +\end{defproblem} diff --git a/shiny/downloadLista/grr b/shiny/downloadLista/grr new file mode 100644 index 0000000000000000000000000000000000000000..9b1e5a772bc02d34bef925e4a160abbb433c7f14 --- /dev/null +++ b/shiny/downloadLista/grr @@ -0,0 +1 @@ +\def\grr{12345678} \ No newline at end of file diff --git a/shiny/downloadLista/lista.tex b/shiny/downloadLista/lista.tex new file mode 100644 index 0000000000000000000000000000000000000000..0c0d7ef144566f517d35fcc27b96ee72fcdae02d --- /dev/null +++ b/shiny/downloadLista/lista.tex @@ -0,0 +1,170 @@ +\documentclass[a4paper]{article} + +%----------------------------------------------------------------------- +%% Incluídos pelo knitr. + +\usepackage[]{graphicx} +\usepackage[]{color} +\makeatletter +\def\maxwidth{ % + \ifdim\Gin@nat@width>\linewidth + \linewidth + \else + \Gin@nat@width + \fi +} +\makeatother + +\definecolor{fgcolor}{rgb}{0.345, 0.345, 0.345} +%\definecolor{fgcolor}{rgb}{0.5, 0.5, 0.5} +\newcommand{\hlnum}[1]{\textcolor[rgb]{0.686,0.059,0.569}{#1}}% +\newcommand{\hlstr}[1]{\textcolor[rgb]{0.192,0.494,0.8}{#1}}% +\newcommand{\hlcom}[1]{\textcolor[rgb]{0.678,0.584,0.686}{\textit{#1}}}% +\newcommand{\hlopt}[1]{\textcolor[rgb]{0,0,0}{#1}}% +\newcommand{\hlstd}[1]{\textcolor[rgb]{0.345,0.345,0.345}{#1}}% +\newcommand{\hlkwa}[1]{\textcolor[rgb]{0.161,0.373,0.58}{\textbf{#1}}}% +\newcommand{\hlkwb}[1]{\textcolor[rgb]{0.69,0.353,0.396}{#1}}% +\newcommand{\hlkwc}[1]{\textcolor[rgb]{0.333,0.667,0.333}{#1}}% +\newcommand{\hlkwd}[1]{\textcolor[rgb]{0.737,0.353,0.396}{\textbf{#1}}}% + +\usepackage{framed} +\makeatletter +\newenvironment{kframe}{% + \def\at@end@of@kframe{}% + \ifinner\ifhmode% + \def\at@end@of@kframe{\end{minipage}}% + \begin{minipage}{\columnwidth}% + \fi\fi% + \def\FrameCommand##1{\hskip\@totalleftmargin \hskip-\fboxsep + \colorbox{shadecolor}{##1}\hskip-\fboxsep + % There is no \\@totalrightmargin, so: + \hskip-\linewidth \hskip-\@totalleftmargin \hskip\columnwidth}% + \MakeFramed {\advance\hsize-\width + \@totalleftmargin\z@ \linewidth\hsize + \@setminipage}}% + {\par\unskip\endMakeFramed% + \at@end@of@kframe} +\makeatother + +\definecolor{shadecolor}{rgb}{.97, .97, .97} +\definecolor{messagecolor}{rgb}{0, 0, 0} +\definecolor{warningcolor}{rgb}{1, 0, 1} +\definecolor{errorcolor}{rgb}{1, 0, 0} +\newenvironment{knitrout}{}{} % an empty environment to be redefined in TeX + +\usepackage{alltt} + +%%----------------------------------------------------------------------------- + +\usepackage[utf8]{inputenc} +\usepackage[brazil]{babel} +\usepackage[T1]{fontenc} +\usepackage{amsmath,amsfonts,mathrsfs,amssymb,amsthm,icomma} +\usepackage{geometry, calc, color, setspace, indentfirst} + \geometry{hmargin={1.7cm,1.7cm}, vmargin={1.7cm,1.7cm}} + +\usepackage{wrapfig} +\usepackage{boxedminipage} + +\usepackage{enumerate} +\usepackage{paralist} + +\usepackage{float} +\usepackage[hang]{caption} +\usepackage{comment} + +\usepackage{multicol} +\usepackage{multirow} % para tabelas +\usepackage{pbox} % quebra de linhas em tabela +\usepackage{colortbl} + +% \usepackage[table, usenames, dvipsnames]{xcolor} +\usepackage{fancyvrb} % permite vebatim dentro de fbox{} +\usepackage[svgnames]{xcolor} +\usepackage[colorlinks, citecolor=DarkRed, linkcolor=DarkGreen, + urlcolor=DarkBlue]{hyperref} + +\usepackage{palatino} +\usepackage{eulervm} +\usepackage[scaled=0.8]{beramono} + +\usepackage{hyperref} + +\usepackage[final]{probsoln} +\setkeys{probsoln}{fragile} % para permitir verbatim no \defproblem{} + +\usepackage{tikz} +\usetikzlibrary{arrows, decorations.pathmorphing, backgrounds, fit, + positioning, calc, trees} +\usepackage{pgfplots} +\pgfplotsset{compat=newest} + +\newtheoremstyle{exercicio} % Configurando um novo estilo de teorema para exercícios + {3pt} % Space above + {3pt} % Space below + {\upshape} % Body font + {} % Indent amount (5pt) + {} %\bfseries\scshape + {.} % Punctuation after theorem head (:;?) + {.5em} % Space after theorem head + {} % Theorem head spec (can be left empty, meaning `normal') +\theoremstyle{exercicio} +\newtheorem{ex}{}[] % {Exercício}[section] + +%----------------------------------------------------------------------------- + +% Linha horizontal divisória. +\newcommand{\HRule}{ + \noindent\rule{\linewidth}{0.2mm} +} + +\renewcommand{\theenumi}{\alph{enumi}} + +% Nome da solução: solução, resposta, resultado. +\renewcommand{\solutionname}{Soluções} + +% Fomatação/estilo como vai aparecer escrito. +\renewenvironment{solution}{ + \begin{center} + \rule{0.7\linewidth}{0.2mm}\\ + \tiny{Solução} + \end{center} +}{} + +% Ambiente para enumerate em linha centralizado. +\newenvironment{clist}{ + \begin{center} + \begin{inparaenum}[a)] + }{ + \end{inparaenum} + \end{center} +} + +%----------------------------------------------------------------------- +\input{grr} + +\begin{document} +\pagestyle{empty} + +\begin{center} + {\Large Lista de exercícios}\\ \today\\ GRR: \grr{} +\end{center} + +\begin{center} + \noindent\rule{0.8\linewidth}{0.2mm}\\ + \vspace*{-1em} + \noindent\rule{0.5\linewidth}{0.2mm} +\end{center} + +\loadallproblems[ex]{exercGRR} + +\foreachproblem[ex]{ + \begin{ex} + \label{prob:\thisproblemlabel} + \thisproblem + \end{ex} + \HRule +} + +\end{document} +\endinput diff --git a/shiny/downloadLista/log b/shiny/downloadLista/log new file mode 100644 index 0000000000000000000000000000000000000000..b2893d900c2991a47ed212b9e41402c5fc7dc259 --- /dev/null +++ b/shiny/downloadLista/log @@ -0,0 +1,5 @@ +12346578 2015-12-01 22:58:49 +12346578 2015-12-01 22:59:09 +12345678 2015-12-01 23:00:48 +12345678 2015-12-01 23:02:29 +12345678 2015-12-01 23:03:18 diff --git a/shiny/downloadLista/server.R b/shiny/downloadLista/server.R new file mode 100644 index 0000000000000000000000000000000000000000..e623acf3a7ccc69efd3a31a7239fe368b0007f31 --- /dev/null +++ b/shiny/downloadLista/server.R @@ -0,0 +1,81 @@ +require(xtable) +require(knitr) +require(shiny) + +shinyServer( + function(input, output, session){ + geraPDF <- + reactive({ + ## Pega GRR + grr <- input$GRR + set.seed(grr) + + ## Embaralha a ordem dos exercícios. + exer <- sample(input$EXER) + validExer <- length(exer)>0 + if (!validExer){ + stop("Nenhum exercício selecionado.") + } + + validGrr <- grepl(x=grr, pattern="^\\d{8}$") + if (!validGrr){ + stop("GRR deve ter 8 digitos numéricos.") + } + + arqbase <- paste0(exer, ".Rnw") + arqresu <- "exercGRR.Rnw" + + ## Lê as linhas. + if (length(arqbase)>1){ + ex <- sapply(arqbase, FUN=readLines) + ex <- lapply(ex, FUN=append, values=rep("", 3)) + rl0 <- do.call(c, ex) + rl0 <- unlist(ex) + names(rl0) <- NULL + } else { + rl0 <- readLines(arqbase) + } + + ## Troca a ocorrência de GRR pelo valor passado. + rl1 <- gsub(pattern="[_]GRR[_]", replacement=grr, x=rl0) + + ## Arquivo texto de uma linha que só contém o GRR. + cat(paste0("\\", "def", "\\", "grr{", grr, "}"), + file="grr") + + ## No caso de ter senha. + if (input$PASSWD=="senha"){ + cat(paste0("\\", "showanswers"), file="grr", + append=TRUE) + } + + ## Escreve em arquivo de texto. + writeLines(text=rl1, con=arqresu) + ## Converte de Rnw para tex. + knit(arqresu, encoding="utf-8") + ## PDF + cmd <- sprintf("pdflatex -jobname=grr%s lista.tex", grr) + ## Rodar 3 vezes por causa do \label{} e \ref{} + ## system(cmd); system(cmd); system(cmd) + system(cmd) + ## Remove objetos auxiliares. + cat(paste(grr, Sys.time()), + file="log", append=TRUE, sep="\n") + }) + + output$DOWNLOADPDF <- + downloadHandler( + filename=function(){ + sprintf("grr%s.pdf", input$GRR) + }, + content=function(file){ + ## Ao clicar no botão, arquivos são criados. + geraPDF() + file.copy(from=sprintf("grr%s.pdf", input$GRR), + to=file, + overwrite=TRUE) + file.remove( + list.files(pattern="\\.(log|out|vrb|pdf|aux)$")) + }, + contentType="application/pdf") + }) diff --git a/shiny/downloadLista/ui.R b/shiny/downloadLista/ui.R new file mode 100644 index 0000000000000000000000000000000000000000..f3528f347d41f49c864b88bb142dd3d6346027f3 --- /dev/null +++ b/shiny/downloadLista/ui.R @@ -0,0 +1,22 @@ +require(shiny) + +choi <- setdiff(x=list.files(pattern="\\.Rnw$"), + y=c("exercGRR.Rnw", "00template.Rnw")) +choi <- gsub(x=choi, pattern="\\.Rnw$", replacement="") + +shinyUI( + fluidPage( + titlePanel("Baixe sua lista de exercícios"), + verticalLayout( + textInput(inputId="GRR", + label="Informe seu GRR (8 números):"), + checkboxGroupInput(inputId="EXER", + label="Selecione os exercícios:", + choices=choi), + passwordInput(inputId="PASSWD", + label="Digite a senha para incluir gabarito:", + value=""), + downloadButton(outputId="DOWNLOADPDF", label="Download") + ) + ) +) diff --git a/shiny/includesHtml/DESCRIPTION b/shiny/includesHtml/DESCRIPTION new file mode 100644 index 0000000000000000000000000000000000000000..f6e92c461f806647311cd820dc0d58586b0a09bb --- /dev/null +++ b/shiny/includesHtml/DESCRIPTION @@ -0,0 +1,7 @@ +Title: Explorando interfaces gráficas interativas no R - 2 +Author: Eduardo E. Ribeiro Jr e Walmes M. Zeviani +AuthorUrl: https://gitlab.c3sl.ufpr.br/pet-estatistica/iguir2 +License: GPL-3 +DisplayMode: Showcase +Tags: iguir2 +Type: Shiny diff --git a/shiny/includesHtml/include.md b/shiny/includesHtml/include.md new file mode 100644 index 0000000000000000000000000000000000000000..71916b17b4bdd1b4f5898f65f11d41048d8e3936 --- /dev/null +++ b/shiny/includesHtml/include.md @@ -0,0 +1,26 @@ +Esse é um arquivo markdown +========================== + +Abaixo temos uma lista de compras: + +* Arroz; +* Açucar; +* Azeite; +* Farinha; +* Feijão; + +## É póssível incluir código + +No arquivo markdown os códigos são renderizados de acordo com a +linguagem definida no *chunk* + +```{r} +## Uma soma do R +x <- 10 +x+ 2 + 1 +``` + +```{sh} +## Para instalar o Git +sudo apt-get install git +``` diff --git a/shiny/includesHtml/include.txt b/shiny/includesHtml/include.txt new file mode 100644 index 0000000000000000000000000000000000000000..143faa885fa6ebeb9f45b68e1b31fdca6d68224d --- /dev/null +++ b/shiny/includesHtml/include.txt @@ -0,0 +1,22 @@ +## Esse é um conjunto de dados de um experimento em DIC. +racoes ganhopeso +A 35 +A 19 +A 31 +A 15 +A 30 +B 40 +B 35 +B 46 +B 41 +B 33 +C 39 +C 27 +C 20 +C 29 +C 45 +D 27 +D 12 +D 13 +D 28 +D 30 diff --git a/shiny/includesHtml/includesHtml.Rproj b/shiny/includesHtml/includesHtml.Rproj new file mode 100644 index 0000000000000000000000000000000000000000..3715d52d2dcf3d8d8b4e5796956246ae2729f2c2 --- /dev/null +++ b/shiny/includesHtml/includesHtml.Rproj @@ -0,0 +1,13 @@ +Version: 1.0 + +RestoreWorkspace: Default +SaveWorkspace: Default +AlwaysSaveHistory: Default + +EnableCodeIndexing: Yes +UseSpacesForTab: Yes +NumSpacesForTab: 4 +Encoding: UTF-8 + +RnwWeave: knitr +LaTeX: pdfLaTeX diff --git a/shiny/includesHtml/server.R b/shiny/includesHtml/server.R new file mode 100644 index 0000000000000000000000000000000000000000..3a5a1a54145acfdb937836508773a0ff75a2ff1c --- /dev/null +++ b/shiny/includesHtml/server.R @@ -0,0 +1,21 @@ +library(shiny) + +shinyServer( + function(input, output) { + output$TEXT <- renderPrint( + cat(paste0( + '<style> p { line-height: ', + input$HEIGHT, + 'pt; } </style>', + '<p><font face="', + input$FONT, + '" font color="', + input$COLOR, + '">Aqui temos um texto qualquer que muda de cor!', + '</font></p>', + '<p><font color="', + input$COLOR, + '">Esse aqui também muda.</font></p>') + ) + ) + }) diff --git a/shiny/includesHtml/ui.R b/shiny/includesHtml/ui.R new file mode 100644 index 0000000000000000000000000000000000000000..04a6a735c0aeb1e6ee492a8bc5c652dceb30fd41 --- /dev/null +++ b/shiny/includesHtml/ui.R @@ -0,0 +1,29 @@ +library(markdown) + +# http://www.w3schools.com/cssref/tryit.asp?filename=trycss_line-height + +shinyUI( + fluidPage( + titlePanel("Título da aplicação"), + navlistPanel( + tabPanel(title="A", + includeText("include.txt")), + tabPanel(title="B", + pre(includeText("include.txt"))), + tabPanel(title="C", + includeHTML("include.html")), + tabPanel(title="D", + includeMarkdown("include.md")), + tabPanel(title="E", + verticalLayout( + selectInput(inputId="COLOR", label="Cor:", + choices=c("red", "blue", "green")), + selectInput(inputId="FONT", label="Fonte:", + choices=c("verdana", "times", + "ubuntu")), + sliderInput(inputId="HEIGHT", label="Espaçamento:", + min=0.25, max=50, value=1, step=0.25), + htmlOutput("TEXT") + )) + ) +)) diff --git a/shiny/layouts/DESCRIPTION b/shiny/layouts/DESCRIPTION new file mode 100644 index 0000000000000000000000000000000000000000..f6e92c461f806647311cd820dc0d58586b0a09bb --- /dev/null +++ b/shiny/layouts/DESCRIPTION @@ -0,0 +1,7 @@ +Title: Explorando interfaces gráficas interativas no R - 2 +Author: Eduardo E. Ribeiro Jr e Walmes M. Zeviani +AuthorUrl: https://gitlab.c3sl.ufpr.br/pet-estatistica/iguir2 +License: GPL-3 +DisplayMode: Showcase +Tags: iguir2 +Type: Shiny diff --git a/shiny/layouts/layouts.Rproj b/shiny/layouts/layouts.Rproj new file mode 100644 index 0000000000000000000000000000000000000000..3715d52d2dcf3d8d8b4e5796956246ae2729f2c2 --- /dev/null +++ b/shiny/layouts/layouts.Rproj @@ -0,0 +1,13 @@ +Version: 1.0 + +RestoreWorkspace: Default +SaveWorkspace: Default +AlwaysSaveHistory: Default + +EnableCodeIndexing: Yes +UseSpacesForTab: Yes +NumSpacesForTab: 4 +Encoding: UTF-8 + +RnwWeave: knitr +LaTeX: pdfLaTeX diff --git a/shiny/layouts/server.R b/shiny/layouts/server.R new file mode 100644 index 0000000000000000000000000000000000000000..f1f8a6fb790fccdcd15bda747e7d9fb48ae92fd0 --- /dev/null +++ b/shiny/layouts/server.R @@ -0,0 +1,6 @@ +library(shiny) + +shinyServer( + function(input, output) { + NULL + }) diff --git a/shiny/layouts/ui.R b/shiny/layouts/ui.R new file mode 100644 index 0000000000000000000000000000000000000000..0098b7b526f002689e2cf04183a048b30e5ed7c9 --- /dev/null +++ b/shiny/layouts/ui.R @@ -0,0 +1,136 @@ +library(shiny) + +apropos("Layout$", ignore.case=FALSE) +apropos("^fluid", ignore.case=FALSE) +apropos("Panel$", ignore.case=FALSE) + +##---------------------------------------------------------------------- +## sidebarLayout() com tabsetPanel(). + +# shinyUI( +# fluidPage( +# titlePanel("Título da aplicação"), +# sidebarLayout( +# sidebarPanel( +# sliderInput(inputId="A", +# label="Elemento A", +# min=0, max=1, step=0.1, value=0.5), +# radioButtons(inputId="B", +# label="Elemento B", +# choices=1:4), +# textInput(inputId="C", +# label="Elemento C", +# value="Um texto qualquer") +# ), +# mainPanel( +# tabsetPanel( +# tabPanel(title="Aba I", +# checkboxGroupInput(inputId="D", +# label="Elemento D", +# choices=1:5)), +# tabPanel(title="Aba II", +# dateRangeInput(inputId="E", +# label="Elemento E")), +# position="right" +# ) +# ) +# ) +# )) + +##---------------------------------------------------------------------- +## splitLayout(), flowLayout() e fluidRow(). + +# shinyUI( +# fluidPage( +# titlePanel("Título da aplicação"), +# splitLayout( +# cellWidths=c("20%", "30%", "50%"), +# # style="border: 1px solid silver;", +# sliderInput(inputId="A", +# label="Elemento A", +# min=0, max=1, step=0.1, value=0.5), +# radioButtons(inputId="B", +# label="Elemento B", +# choices=1:4), +# textInput(inputId="C", +# label="Elemento C", +# value="Um texto qualquer") +# ), +# flowLayout( +# numericInput(inputId="D", +# label="Número de cervejas", value=5), +# selectInput(inputId="E", +# label="Qual cerveja?", +# choices=c("Skol", "Antartica", "Brahma")), +# sliderInput(inputId="F", +# label="Que temperatura?", +# min=-6, max=5, value=0, step=0.5) +# ), +# fluidRow( +# column(width=3, +# sliderInput(inputId="G", +# label="Tamanho da amostra", +# min=5, max=100, value=30, step=5), +# checkboxInput(inputId="H", +# label="Com reposição?") +# ), +# column(width=4, offset=1, +# sliderInput(inputId="I", label="Média", +# 10, 20, 15, 0.1), +# sliderInput(inputId="J", label="Variância", +# 1, 7, 2, 0.1) +# ), +# column(width=2, +# textInput(inputId="L", label="Nome"), +# textInput(inputId="K", label="Email") +# ) +# ) +# )) + +##---------------------------------------------------------------------- +## verticalLayout() e navlistPanel(). + +shinyUI( + fluidPage( + titlePanel("Título da aplicação"), + verticalLayout( + navlistPanel( + tabPanel(title="Primeiro", + sliderInput(inputId="A", + label="Elemento A", + min=0, max=1, step=0.1, value=0.5), + radioButtons(inputId="B", + label="Elemento B", + choices=1:4)), + tabPanel(title="Segundo", + textInput(inputId="C", + label="Elemento C", + value="Um texto qualquer"), + numericInput(inputId="D", + label="Número de cervejas", + value=5), + selectInput(inputId="E", + label="Qual cerveja?", + choices=c("Skol", "Antartica", + "Brahma")), + sliderInput(inputId="F", + label="Que temperatura?", + min=-6, max=5, value=0, step=0.5)), + tabPanel(title="Terceiro", + sliderInput(inputId="G", + label="Tamanho da amostra", + min=5, max=100, value=30, step=5), + checkboxInput(inputId="H", + label="Com reposição?"), + sliderInput(inputId="I", label="Média", + 10, 20, 15, 0.1), + sliderInput(inputId="J", label="Variância", + 1, 7, 2, 0.1), + textInput(inputId="L", label="Nome"), + textInput(inputId="K", label="Email")) + ) + ) + )) + +##---------------------------------------------------------------------- +## wellPanel() e tagList(). diff --git a/shiny/process/DESCRIPTION b/shiny/process/DESCRIPTION new file mode 100644 index 0000000000000000000000000000000000000000..f6e92c461f806647311cd820dc0d58586b0a09bb --- /dev/null +++ b/shiny/process/DESCRIPTION @@ -0,0 +1,7 @@ +Title: Explorando interfaces gráficas interativas no R - 2 +Author: Eduardo E. Ribeiro Jr e Walmes M. Zeviani +AuthorUrl: https://gitlab.c3sl.ufpr.br/pet-estatistica/iguir2 +License: GPL-3 +DisplayMode: Showcase +Tags: iguir2 +Type: Shiny diff --git a/shiny/process/process.Rproj b/shiny/process/process.Rproj new file mode 100644 index 0000000000000000000000000000000000000000..3715d52d2dcf3d8d8b4e5796956246ae2729f2c2 --- /dev/null +++ b/shiny/process/process.Rproj @@ -0,0 +1,13 @@ +Version: 1.0 + +RestoreWorkspace: Default +SaveWorkspace: Default +AlwaysSaveHistory: Default + +EnableCodeIndexing: Yes +UseSpacesForTab: Yes +NumSpacesForTab: 4 +Encoding: UTF-8 + +RnwWeave: knitr +LaTeX: pdfLaTeX diff --git a/shiny/process/report.Rnw b/shiny/process/report.Rnw new file mode 100644 index 0000000000000000000000000000000000000000..d5bc469f79913d39e6797f097895a79173f7c78c --- /dev/null +++ b/shiny/process/report.Rnw @@ -0,0 +1,18 @@ +\documentclass{article} + +\begin{document} + +<<include=FALSE>>= +library(xtable) +@ + +<<>>= +load("image.RData") +str(x) +@ + +<<results="asis">>= +xtable(x, caption="Tabela dos dados analizados.") +@ + +\end{document} \ No newline at end of file diff --git a/shiny/process/server.R b/shiny/process/server.R new file mode 100644 index 0000000000000000000000000000000000000000..ac6e2043cf69e4c187f8b6b0b6c358f4c096d8d3 --- /dev/null +++ b/shiny/process/server.R @@ -0,0 +1,28 @@ +library(shiny) +library(knitr) + +shinyServer( + function(input, output) { + output$TABLE <- renderTable( + get(input$DATASET) + ) + output$DOWNLOAD_PDF <- downloadHandler( + filename=function(){ + return("report.pdf") + }, + content=function(file){ + ## Pega objeto e salva imagem com ele. + x <- get(isolate(input$DATASET)) + save(x, file="image.RData") + ## Rnw -> tex -> pdf. + knit2pdf(input="report.Rnw") + ## Empurra o arquivo para download. + file.copy(from="report.pdf", + to=file, + overwrite=TRUE) + ## Remove arquivos auxiliares descessários. + file.remove(list.files( + pattern="\\.(log|out|vrb|pdf)$")) + }, + contentType="application/pdf") + }) diff --git a/shiny/process/ui.R b/shiny/process/ui.R new file mode 100644 index 0000000000000000000000000000000000000000..6c74451285ddf8ba4a685d0e4864a3c831ab98e8 --- /dev/null +++ b/shiny/process/ui.R @@ -0,0 +1,18 @@ +library(shiny) + +shinyUI( + fluidPage( + titlePanel("Download do relatório"), + sidebarLayout( + sidebarPanel( + selectInput(inputId="DATASET", + label="Escolha o conjunto de dados:", + choices=c("cars", "mtcars", "iris")), + downloadButton(outputId="DOWNLOAD_PDF", + label="Download") + ), + mainPanel( + tableOutput("TABLE") + ) + ) + )) diff --git a/shiny/regPoly/DESCRIPTION b/shiny/regPoly/DESCRIPTION new file mode 100644 index 0000000000000000000000000000000000000000..f6e92c461f806647311cd820dc0d58586b0a09bb --- /dev/null +++ b/shiny/regPoly/DESCRIPTION @@ -0,0 +1,7 @@ +Title: Explorando interfaces gráficas interativas no R - 2 +Author: Eduardo E. Ribeiro Jr e Walmes M. Zeviani +AuthorUrl: https://gitlab.c3sl.ufpr.br/pet-estatistica/iguir2 +License: GPL-3 +DisplayMode: Showcase +Tags: iguir2 +Type: Shiny diff --git a/shiny/regPoly/regPoly.Rproj b/shiny/regPoly/regPoly.Rproj new file mode 100644 index 0000000000000000000000000000000000000000..3715d52d2dcf3d8d8b4e5796956246ae2729f2c2 --- /dev/null +++ b/shiny/regPoly/regPoly.Rproj @@ -0,0 +1,13 @@ +Version: 1.0 + +RestoreWorkspace: Default +SaveWorkspace: Default +AlwaysSaveHistory: Default + +EnableCodeIndexing: Yes +UseSpacesForTab: Yes +NumSpacesForTab: 4 +Encoding: UTF-8 + +RnwWeave: knitr +LaTeX: pdfLaTeX diff --git a/shiny/regPoly/server.R b/shiny/regPoly/server.R new file mode 100644 index 0000000000000000000000000000000000000000..0301f15b71cb9868d2af1e22a7580dc101a4d817 --- /dev/null +++ b/shiny/regPoly/server.R @@ -0,0 +1,64 @@ +library(shiny) + +apropos("^update[A-Z]", ignore.case=FALSE) + +get("cars") + +shinyServer(function(input, output, session){ + observe({ + da <- get(input$DATASET) + updateSelectInput(session, + inputId="Y", + choices=names(da), + selected=names(da)[1]) + updateSelectInput(session, + inputId="X", + choices=names(da), + selected=names(da)[2]) + }) + REATIVA <- reactive({ + DADOS <- get(input$DATASET) + DADOS <- DADOS[, c(input$X, input$Y)] + names(DADOS) <- c("x", "y") + if (input$TRANSFORM){ + DADOS$y <- do.call(input$TRANSFUN, list(DADOS$y)) + } + MODELO <- lm(y~poly(x, degree=input$DEGREE, raw=TRUE), + data=DADOS) + return(list(DADOS=DADOS, MODELO=MODELO)) + }) + output$AJUSTE <- renderPlot({ + da <- REATIVA()$DADOS + m0 <- REATIVA()$MODELO + pred <- data.frame(x=seq(min(da[,"x"]), max(da[,"x"]), l=50)) + a <- predict(m0, newdata=pred, interval="confidence") + pred <- cbind(pred, a) + plot(da[,"y"]~da[,"x"], xlab="x", ylab="y") + matlines(x=pred[,1], pred[,2:4], lty=c(1,2,2), col=1) + }, width=600, height=600) + output$ANOVA_SUMMARY <- renderPrint({ + m0 <- REATIVA()$MODELO + cat("------------------------------------------------------------", + capture.output(anova(m0))[-(7:8)], + "------------------------------------------------------------", + capture.output(summary(m0))[-c(1:9)], + "------------------------------------------------------------", + sep="\n") + }) + output$RESIDUOS <- renderPlot({ + par(mfrow=c(2,2)) + plot(REATIVA()$MODELO) + layout(1) + }, width=600, height=600) +# output$INFLUENCE <- renderDataTable({ +# im <- influence.measures(REATIVA()$MODELO) +# colnames(im$infmat)[1:2] <- c("db.b0", "db.b1") +# formatC(x=round(im$infmat, digits=2), +# digits=2, format="f") +# }) + output$INFLUENCE <- renderTable({ + im <- influence.measures(REATIVA()$MODELO) + colnames(im$infmat)[1:2] <- c("db.b0", "db.b1") + im$infmat + }, digits=4) +}) diff --git a/shiny/regPoly/ui.R b/shiny/regPoly/ui.R new file mode 100644 index 0000000000000000000000000000000000000000..c0ad0478ab6189e36fb3e911e2f9320988121d95 --- /dev/null +++ b/shiny/regPoly/ui.R @@ -0,0 +1,52 @@ +library(shiny) + +ds <- c("swiss", "cars", "longley", "iris", "rock") + +shinyUI(fluidPage( + titlePanel("Regressão Polinomial"), + p("CE 064 - Ferramentas para documentos dinâmicos reproduzíveis - 2015/2"), + hr(), + sidebarLayout( + sidebarPanel( + selectInput(inputId="DATASET", + label="Escolha o conjunto de dados:", + choices=ds, + selected="swiss"), + selectInput(inputId="Y", + label="Variável dependente:", + choices=names(swiss), + selected=names(swiss)[1]), + selectInput(inputId="X", + label="Variável independente:", + choices=names(swiss), + selected=names(swiss)[2]), + numericInput(inputId="DEGREE", + label="Grau do polinômio:", + min=1, max=5, value=1, step=1), + checkboxInput(inputId="TRANSFORM", + label="Transformar Y?"), + conditionalPanel("input.TRANSFORM", + radioButtons(inputId="TRANSFUN", + label="Escolha a transformação:", + choices=c("sqrt", "log"), + selected="sqrt")) + ), + mainPanel( + tabsetPanel( + tabPanel(title="Ajuste...", + h3("Valores observados e modelo ajustado"), + plotOutput("AJUSTE")), + tabPanel(title="Estimativas...", + h3("Medidas de ajuste e estimativas dos parâmetros"), + verbatimTextOutput("ANOVA_SUMMARY")), + tabPanel(title="Resíduos...", + h3("Gráficos para diagnóstico do ajuste"), + plotOutput("RESIDUOS")), + tabPanel(title="Influência...", + h3("Medidas de influência"), + # dataTableOutput("INFLUENCE") + tableOutput("INFLUENCE") + )) + ) + ) +))