“Sacándole Partido al RStudio” 1480-Técnicas Estadísticas...

Post on 18-Aug-2020

4 views 0 download

Transcript of “Sacándole Partido al RStudio” 1480-Técnicas Estadísticas...

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

RSTUDIO:ELGIGANTEDORMIDO

TiposdeDocumentos

• EnRStudio podemoshacermás cosasapartedecrearunarchivo*.Rconunasintaxisyejecutarla.

• Podemos:– Crearunproyectoyolvidarnosdedóndeguardamoslascosas

– Generarsalidasdelosresultadosdeformaatractiva• HTML5,LATEX,WORD,etc.

OpcionesdeRStudio

OpcionesdeRStudio

OpcionesdeRStudio

CreandounNuevoProyecto

• Archivoà NuevoProyecto

TipodeDocumentoaCrear

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

MARKDOWN

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.

Markdown

• Enesteenlacepodréis encontrarunbuenresumendecómofuncionaMarkdown enRstudio:Enlace.

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

library(rmarkdown)

library(knitr)

Markdown Example (I)

Markdown Example (I)

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

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"))```

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"))```

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")```

Shiny:creando aplicaciones web desde 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")

Shiny

Shiny

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

• Sepuedeprobaranivellocal,obin enunrepositorioomásanivelprofesionaldesdeunRstudio Server.

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')})

})

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")))

))

CreandoHTML

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>

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)

```

Rpresentation