siemre usar file y buscar rmarkdown

Bbliotecas utiles

“library(tidyverse)” “library(kableExtra)” “library(readxl)” “library(dplyr)”

Cargar bases de datos

data(nombre)

visualizar la base

head(nombre)

resumir con algunas estadísticas las variables de la base

summary(nombre)

Hacer una grafica simple

hist(nombre de la variable)

Concatenar datos

variable nueva=data.frame(variable,variable)

Crear datos

edad<-c(11,12,15,20,41)
edad
## [1] 11 12 15 20 41
altura=c(50,65,120,156,182)
altura
## [1]  50  65 120 156 182
datos=data.frame(edad,altura)
datos

Hacer graficos de barras

recordar cargar paquete de ggplot2 introducir datos para generar una tabla y df es el nombre

df <- data.frame(Empresa = 
                   c("Disney World", 
                      "Florida Hospital", 
                      "Publix Supermarkets Inc",
                      "Walmart Stores Ind",
                      "Univaersal Orlando"), 
                 Asalariados = 
                   c(51600,
                     19283,
                     14995,
                     14995,
                     12000))
knitr::kable(df)
Empresa Asalariados
Disney World 51600
Florida Hospital 19283
Publix Supermarkets Inc 14995
Walmart Stores Ind 14995
Univaersal Orlando 12000
library(ggplot2)
ggplot(data=df, aes(x=Empresa, y=Asalariados)) + geom_bar(stat="identity")

library(ggplot2)
ggplot(data=df, aes(x=Empresa, y=Asalariados)) + geom_bar(stat="identity") + coord_flip()

para publicar lo trabajado dar en knit y poner un nombre para descargar ir a la parte derecha y buscar el logo azul de ajustes y dar exportar

Podemos cambiar el ancho, así como también el color de las barras y bordes.

Ancho

ggplot(data=df, aes(x=Empresa, y=Asalariados)) + geom_bar(stat="identity", width=0.5)

colores

ggplot(data=df, aes(x=Empresa, y=Asalariados)) + geom_bar(stat="identity", color="blue", fill="white")

si se quiere puede copiarse la grafica a una variable (p) para editarla

p <- ggplot(data=df, aes(x=Empresa, y=Asalariados)) + geom_bar(stat="identity", fill="steelblue") + theme_minimal()
p

# Grafico de barras agrupados crear datos que se usaran: Número de estudiantes matriculados en tres especialidades de administración de empresas, 2000 y 2005. Creamos un data frame a partir de la tabla de frecuencias que contenga tres columnas, cada una representando la especialidad, el año, y el número de matriculados.

df <- data.frame(Especialidad = c(rep("Finanzas", 2), 
                                  rep("Marketing", 2), 
                                  rep("Contabilidad", 2)),
                 Año = rep(c(2000, 2005), 3),
                 Matriculados = c(160, 250,
                                  140, 200,
                                  100, 150))
knitr::kable(df)
Especialidad Año Matriculados
Finanzas 2000 160
Finanzas 2005 250
Marketing 2000 140
Marketing 2005 200
Contabilidad 2000 100
Contabilidad 2005 150

Grafico

ggplot(df, aes(fill = Especialidad, y = Matriculados, x = Año)) +
  geom_bar(position="dodge", stat="identity", color = "black") +
  scale_fill_manual(values = c("red", "yellow","green"))

Grafico apilado

ggplot(df, aes(fill = Especialidad, y = Matriculados, x = Año)) +
  geom_bar(position="stack", stat="identity", color = "black") +
  scale_fill_manual(values = c("red", "yellow","green"))

# Diagrama circular El gerente de una empresa observó que el 31 por ciento de los gastos estaba representado por los costes de transporte, el 25 por ciento por los costes de alojamiento, el 12 por ciento por los gastos de alimentación, el 20 por ciento por los gastos de matrícula y el resto por costes varios.

crear tabla de datos

library(ggplot2)
library(dplyr)
## 
## Attaching package: 'dplyr'
## The following objects are masked from 'package:stats':
## 
##     filter, lag
## The following objects are masked from 'package:base':
## 
##     intersect, setdiff, setequal, union
data <- data.frame(group = 
                     c("Transporte", 
                       "Alojamiento", 
                       "Alimentaión", 
                       "Gastos de matricula",
                       "Varios"), 
                   value = c(31, 25, 12, 20, 12))
knitr::kable(data)
group value
Transporte 31
Alojamiento 25
Alimentaión 12
Gastos de matricula 20
Varios 12

crear grafico

ggplot(data, aes(x = "", y = value, fill=group)) +
  geom_bar(stat = "identity", width = 1) +
  coord_polar("y", start = 0)

library(ggplot2)
library(dplyr)

data <- data %>% 
  arrange(desc(group)) %>%
  mutate(prop = value / sum(data$value) *100) %>%
  mutate(ypos = cumsum(prop)- 0.5*prop )
require(scales)
## Loading required package: scales
ggplot(data, aes(x="", y = prop, fill=group)) +
  geom_bar(stat="identity", width=1, color="white") +
  coord_polar("y", start=0) +
  theme_void() + 
  theme(legend.position="none") +
  
  geom_text(aes(y = ypos, label = percent(value/100)), color = "white", size=6) +
  scale_fill_brewer(palette="Set1")

los grfaicos de pareto y tallo y hojas estan en la presentación

Graficos de series de tiempo

importar datos y leerlos de una fuente externa

library(readr)
## 
## Attaching package: 'readr'
## The following object is masked from 'package:scales':
## 
##     col_factor
library(knitr)  

df <- read_csv("https://raw.githubusercontent.com/lihkir/AnalisisEstadisticoUN/main/Data/annual_csv.csv")
## Rows: 274 Columns: 3
## ── Column specification ────────────────────────────────────────────────────────
## Delimiter: ","
## chr (1): Source
## dbl (2): Year, Mean
## 
## ℹ Use `spec()` to retrieve the full column specification for this data.
## ℹ Specify the column types or set `show_col_types = FALSE` to quiet this message.
knitr::kable(head(df))
Source Year Mean
GCAG 2016 0.9363
GISTEMP 2016 0.9900
GCAG 2015 0.8998
GISTEMP 2015 0.8700
GCAG 2014 0.7408
GISTEMP 2014 0.7400

generar grafica

library(ggplot2)
library(dplyr)

ggplot(df, aes(x = Year, y = Mean)) +
  geom_line(color="#69b3a2", size = 1) +
  xlab("Year")
## Warning: Using `size` aesthetic for lines was deprecated in ggplot2 3.4.0.
## ℹ Please use `linewidth` instead.
## This warning is displayed once every 8 hours.
## Call `lifecycle::last_lifecycle_warnings()` to see where this warning was
## generated.