“sacándole partido al rstudio” 1480-técnicas estadísticas...

29
Sesión 002. “Sacándole Partido al RStudio” 1480-Técnicas Estadísticas en Investigación de Mercados Grado en Estadística empresaria Profesor: Xavier Barber i Vallés Departamento: Estadística, Matemáticas e Informática

Upload: others

Post on 18-Aug-2020

0 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: “Sacándole Partido al RStudio” 1480-Técnicas Estadísticas ...umh1480.edu.umh.es/wp-content/uploads/sites/44/2013/02/teim_ses… · Sesión 002. “Sacándole Partido al RStudio”

Sesión002.“SacándolePartidoalRStudio”1480-TécnicasEstadísticasenInvestigacióndeMercadosGradoenEstadísticaempresariaProfesor:XavierBarberiVallésDepartamento:Estadística,MatemáticaseInformática

Page 2: “Sacándole Partido al RStudio” 1480-Técnicas Estadísticas ...umh1480.edu.umh.es/wp-content/uploads/sites/44/2013/02/teim_ses… · Sesión 002. “Sacándole Partido al RStudio”

RSTUDIO:ELGIGANTEDORMIDO

Page 3: “Sacándole Partido al RStudio” 1480-Técnicas Estadísticas ...umh1480.edu.umh.es/wp-content/uploads/sites/44/2013/02/teim_ses… · Sesión 002. “Sacándole Partido al RStudio”

TiposdeDocumentos

• EnRStudio podemoshacermás cosasapartedecrearunarchivo*.Rconunasintaxisyejecutarla.

• Podemos:– Crearunproyectoyolvidarnosdedóndeguardamoslascosas

– Generarsalidasdelosresultadosdeformaatractiva• HTML5,LATEX,WORD,etc.

Page 4: “Sacándole Partido al RStudio” 1480-Técnicas Estadísticas ...umh1480.edu.umh.es/wp-content/uploads/sites/44/2013/02/teim_ses… · Sesión 002. “Sacándole Partido al RStudio”

OpcionesdeRStudio

Page 5: “Sacándole Partido al RStudio” 1480-Técnicas Estadísticas ...umh1480.edu.umh.es/wp-content/uploads/sites/44/2013/02/teim_ses… · Sesión 002. “Sacándole Partido al RStudio”

OpcionesdeRStudio

Page 6: “Sacándole Partido al RStudio” 1480-Técnicas Estadísticas ...umh1480.edu.umh.es/wp-content/uploads/sites/44/2013/02/teim_ses… · Sesión 002. “Sacándole Partido al RStudio”

OpcionesdeRStudio

Page 7: “Sacándole Partido al RStudio” 1480-Técnicas Estadísticas ...umh1480.edu.umh.es/wp-content/uploads/sites/44/2013/02/teim_ses… · Sesión 002. “Sacándole Partido al RStudio”

CreandounNuevoProyecto

• Archivoà NuevoProyecto

Page 8: “Sacándole Partido al RStudio” 1480-Técnicas Estadísticas ...umh1480.edu.umh.es/wp-content/uploads/sites/44/2013/02/teim_ses… · Sesión 002. “Sacándole Partido al RStudio”

TipodeDocumentoaCrear

• SintaxisoCódigodeR• DocumentotipoMarkdown• AplicaciónWebdeShiny• ArchivodeTexto• SintaxisocódigodeC++• DocumentotipoSwave• HTML• UnapresentacióndeR• UnarchivodeDocumentaciondeR

Page 9: “Sacándole Partido al RStudio” 1480-Técnicas Estadísticas ...umh1480.edu.umh.es/wp-content/uploads/sites/44/2013/02/teim_ses… · Sesión 002. “Sacándole Partido al RStudio”

MARKDOWN

Page 10: “Sacándole Partido al RStudio” 1480-Técnicas Estadísticas ...umh1480.edu.umh.es/wp-content/uploads/sites/44/2013/02/teim_ses… · Sesión 002. “Sacándole Partido al RStudio”

Markdown

• Markdown es un lenguaje de marcado quefacilita la aplicación de formato a un textoempleando una serie de caracteres de unaforma especial.

• En principio, fue pensado para elaborar textoscuyo destino iba a ser la web con más rapidezy sencillez que si estuviésemos empleandodirectamenteHTML.

Page 11: “Sacándole Partido al RStudio” 1480-Técnicas Estadísticas ...umh1480.edu.umh.es/wp-content/uploads/sites/44/2013/02/teim_ses… · Sesión 002. “Sacándole Partido al RStudio”

Markdown

• Enesteenlacepodréis encontrarunbuenresumendecómofuncionaMarkdown enRstudio:Enlace.

Page 12: “Sacándole Partido al RStudio” 1480-Técnicas Estadísticas ...umh1480.edu.umh.es/wp-content/uploads/sites/44/2013/02/teim_ses… · Sesión 002. “Sacándole Partido al RStudio”

Markdown Ejemplo(I)install.packages("rmarkdown")install.packages("knitr")

library(rmarkdown)

library(knitr)

Page 13: “Sacándole Partido al RStudio” 1480-Técnicas Estadísticas ...umh1480.edu.umh.es/wp-content/uploads/sites/44/2013/02/teim_ses… · Sesión 002. “Sacándole Partido al RStudio”

Markdown Example (I)

Page 14: “Sacándole Partido al RStudio” 1480-Técnicas Estadísticas ...umh1480.edu.umh.es/wp-content/uploads/sites/44/2013/02/teim_ses… · Sesión 002. “Sacándole Partido al RStudio”

Markdown Example (I)

Page 15: “Sacándole Partido al RStudio” 1480-Técnicas Estadísticas ...umh1480.edu.umh.es/wp-content/uploads/sites/44/2013/02/teim_ses… · Sesión 002. “Sacándole Partido al RStudio”

Markdown Example (II)– eval TRUE Whether toevaluate the code andinclude its

results– echo TRUE Whether todisplay code alongwith its results

– warning TRUE Whether todisplaywarnings– error FALSE Whether todisplay errors– message TRUE Whether todisplaymessages– tidy FALSE Whether toreformat code inatidyway when

displaying it– results "markup" "markup","asis","hold",or "hide"– cache FALSE Whether tocacheresults for future renders– comment "##" Comment character topreface resultswith– fig.width 7 Width ininches for plots created inchunk– fig.height 7 Height ininches for plots created inchunk

Page 16: “Sacándole Partido al RStudio” 1480-Técnicas Estadísticas ...umh1480.edu.umh.es/wp-content/uploads/sites/44/2013/02/teim_ses… · Sesión 002. “Sacándole Partido al RStudio”

Markdown Example (II)## creando dos variables X e Y

```{r }x <- 1:10y <- round(rnorm(10, x, 1), 2)df <- data.frame(x, y)df```

### y ahora la salida de esto: ```{r , results='asis', echo=FALSE}cat("Here are some dot points\n\n")cat(paste("* The value of y[", 1:3, "] is ", y[1:3],

sep="", collapse="\n"))```

Page 17: “Sacándole Partido al RStudio” 1480-Técnicas Estadísticas ...umh1480.edu.umh.es/wp-content/uploads/sites/44/2013/02/teim_ses… · Sesión 002. “Sacándole Partido al RStudio”

Markdown Example (II)## creando dos variables X e Y

```{r }

x <- 1:10

y <- round(rnorm(10, x, 1), 2)

df <- data.frame(x, y)

df```

### y ahora la salida de esto:

```{r , results='asis', echo=FALSE}

cat("Here are some dot points\n\n")

cat(paste("* The value of y[", 1:3, "] is ", y[1:3],

sep="", collapse="\n"))```

Page 18: “Sacándole Partido al RStudio” 1480-Técnicas Estadísticas ...umh1480.edu.umh.es/wp-content/uploads/sites/44/2013/02/teim_ses… · Sesión 002. “Sacándole Partido al RStudio”

Markdow Example (III)## Una tabla

```{r , results='asis', echo=FALSE}

cat("x | y", "--- | ---", sep="\n")

cat(apply(df, 1, function(X) paste(X,

collapse=" | ")), sep = "\n")```

Page 19: “Sacándole Partido al RStudio” 1480-Técnicas Estadísticas ...umh1480.edu.umh.es/wp-content/uploads/sites/44/2013/02/teim_ses… · Sesión 002. “Sacándole Partido al RStudio”

Shiny:creando aplicaciones web desde rstudio

Page 20: “Sacándole Partido al RStudio” 1480-Técnicas Estadísticas ...umh1480.edu.umh.es/wp-content/uploads/sites/44/2013/02/teim_ses… · Sesión 002. “Sacándole Partido al RStudio”

¿QuéesShiny?Creaaplicacioneswebinteractivas(apps)desdeR.

• Shiny es una herramienta para crearfácilmente aplicaciones web interactivas(apps) que permiten a los usuarios interactuarcon sus datos sin tener que manipular elcódigo.

install.packages("shiny")library(shiny)runExample("01_hello")

Page 21: “Sacándole Partido al RStudio” 1480-Técnicas Estadísticas ...umh1480.edu.umh.es/wp-content/uploads/sites/44/2013/02/teim_ses… · Sesión 002. “Sacándole Partido al RStudio”

Shiny

Page 22: “Sacándole Partido al RStudio” 1480-Técnicas Estadísticas ...umh1480.edu.umh.es/wp-content/uploads/sites/44/2013/02/teim_ses… · Sesión 002. “Sacándole Partido al RStudio”

Shiny

• Senecesitaun“script”queserálainterface yotra“script”queseráelserver:– Server.R– ui.R

• Sepuedeprobaranivellocal,obin enunrepositorioomásanivelprofesionaldesdeunRstudio Server.

Page 23: “Sacándole Partido al RStudio” 1480-Técnicas Estadísticas ...umh1480.edu.umh.es/wp-content/uploads/sites/44/2013/02/teim_ses… · Sesión 002. “Sacándole Partido al RStudio”

Shiny: server.Rlibrary(shiny)

#Defineserverlogic required todraw ahistogramshinyServer(function(input,output){

#Expression that generates ahistogram.The expression is#wrapped inacall torenderPlot toindicate that:##1)It is "reactive" and therefore should be automatically#re-executed when inputs change#2)Its output typeis aplot

output$distPlot <- renderPlot({x<- faithful[,2]#OldFaithful Geyser databins <- seq(min(x),max(x),length.out =input$bins +1)

#drawthe histogram with the specified number of binshist(x,breaks =bins,col ='darkgray',border ='white')})

})

Page 24: “Sacándole Partido al RStudio” 1480-Técnicas Estadísticas ...umh1480.edu.umh.es/wp-content/uploads/sites/44/2013/02/teim_ses… · Sesión 002. “Sacándole Partido al RStudio”

Shiny:ui.Rlibrary(shiny)#DefineUIfor application that draws ahistogramshinyUI(fluidPage(

#Application titletitlePanel("Hello Shiny!"),

#Sidebar with asliderinputfor the number ofbinssidebarLayout(sidebarPanel(sliderInput("bins",

"Numberofbins:",min=1,max =50,value =30)

),

#Showaplot of the generateddistributionmainPanel(plotOutput("distPlot")))

))

Page 25: “Sacándole Partido al RStudio” 1480-Técnicas Estadísticas ...umh1480.edu.umh.es/wp-content/uploads/sites/44/2013/02/teim_ses… · Sesión 002. “Sacándole Partido al RStudio”

CreandoHTML

Page 26: “Sacándole Partido al RStudio” 1480-Técnicas Estadísticas ...umh1480.edu.umh.es/wp-content/uploads/sites/44/2013/02/teim_ses… · Sesión 002. “Sacándole Partido al RStudio”

CreandoHTML<html>

<head><title>Title</title></head>

<body>

<p>ThisisanRHTMLdocument.Whenyouclickthe<b>KnitHTML</b>buttonawebpagewillbegeneratedthatincludesbothcontentaswellastheoutputofanyembeddedRcodechunkswithinthedocument.YoucanembedanRcodechunklikethis:</p>

<!--begin.rcodesummary(cars)end.rcode-->

<p>Youcanalsoembedplots,forexample:</p>

<!--begin.rcode fig.width=7,fig.height=6plot(cars)end.rcode-->

</body></html>

Page 27: “Sacándole Partido al RStudio” 1480-Técnicas Estadísticas ...umh1480.edu.umh.es/wp-content/uploads/sites/44/2013/02/teim_ses… · Sesión 002. “Sacándole Partido al RStudio”
Page 28: “Sacándole Partido al RStudio” 1480-Técnicas Estadísticas ...umh1480.edu.umh.es/wp-content/uploads/sites/44/2013/02/teim_ses… · Sesión 002. “Sacándole Partido al RStudio”

Rpresentation002_R_presentation

========================================================

author:

date:

autosize: true

First Slide

========================================================

For more details on authoring R presentations please visit <https://support.rstudio.com/hc/en-us/articles/200486468>.

- Bullet 1

- Bullet 2

- Bullet 3

Slide With Code

========================================================

```{r}

summary(cars)

```

Slide With Plot

========================================================

```{r, echo=FALSE}

plot(cars)

```

Page 29: “Sacándole Partido al RStudio” 1480-Técnicas Estadísticas ...umh1480.edu.umh.es/wp-content/uploads/sites/44/2013/02/teim_ses… · Sesión 002. “Sacándole Partido al RStudio”

Rpresentation