RECODIFICAR: tablas desde excel y formateo
link="https://docs.google.com/spreadsheets/d/e/2PACX-1vTFp8tPWkUD3qMcuXsqySAHJUZBoIjiFb_pyIJfTiQAK070YNo8G__7wOD_nl_UPYdWnMbW7I5VbRxr/pub?gid=477181888&single=true&output=csv"
A=read.csv("https://docs.google.com/spreadsheets/d/e/2PACX-1vTFp8tPWkUD3qMcuXsqySAHJUZBoIjiFb_pyIJfTiQAK070YNo8G__7wOD_nl_UPYdWnMbW7I5VbRxr/pub?gid=477181888&single=true&output=csv", stringsAsFactors = F,na.strings = '')
#ojo:No olvides que los numeros deben tener puntos y no comas.Entonces cambiarlo en idioma mexico
str(A)
## 'data.frame': 600 obs. of 13 variables:
## $ ID : int 1 2 3 4 5 6 7 8 9 10 ...
## $ SEX : chr "HOMBRE" "MUJER" "HOMBRE" "HOMBRE" ...
## $ RACE : chr "ASIATICO" "ASIATICO" "ASIATICO" "ASIATICO" ...
## $ SES : chr "ALTO" "ALTO" "ALTO" "MEDIO" ...
## $ SCTYP : chr "PUBLICA" "PUBLICA" "PUBLICA" "PUBLICA" ...
## $ LOCUS : num 0.29 -0.42 0.71 0.06 0.22 0.46 0.44 0.68 0.06 0.05 ...
## $ CONCPT: num 0.88 0.03 0.03 0.03 -0.28 0.03 -0.47 0.25 0.56 0.15 ...
## $ MOT : num 0.67 0.33 0.67 0 0 0 0.33 1 0.33 1 ...
## $ RDG : num 33.6 46.9 41.6 38.9 36.3 49.5 62.7 44.2 46.9 44.2 ...
## $ WRTG : num 43.7 35.9 59.3 41.1 48.9 46.3 64.5 51.5 41.1 49.5 ...
## $ MATH : num 40.2 41.9 41.9 32.7 39.5 46.2 48 36.9 45.3 40.5 ...
## $ SCI : num 39 36.3 44.4 41.7 41.7 41.7 63.4 49.8 47.1 39 ...
## $ CIV : num 40.6 45.6 45.6 40.6 45.6 35.6 55.6 55.6 55.6 50.6 ...
Recodificar o FORMATEO:
A[,c(6:13)]=lapply(A[,c(6:13)], as.numeric)
ojo:en este caso no hay necesidad de hacer el as numeric pórque esta bien,pero si tuvieras que formatear… NO OLVIDAR :si deseas solo cambiar 1 variable que es Numerica …
ejemplo: #A\(score2016=as.nunumeric(A\)score2016)
A[,c(1:3,5)]=lapply(A[,c(1:3,5)], as.factor)
A$SES=as.ordered(A$SES)
str(A)
## 'data.frame': 600 obs. of 13 variables:
## $ ID : Factor w/ 600 levels "1","2","3","4",..: 1 2 3 4 5 6 7 8 9 10 ...
## $ SEX : Factor w/ 2 levels "HOMBRE","MUJER": 1 2 1 1 1 2 2 1 2 1 ...
## $ RACE : Factor w/ 4 levels "ASIATICO","BLANCO",..: 1 1 1 1 1 1 1 1 1 1 ...
## $ SES : Ord.factor w/ 3 levels "ALTO"<"BAJO"<..: 1 1 1 3 3 3 1 1 3 1 ...
## $ SCTYP : Factor w/ 2 levels "PRIVADA","PUBLICA": 2 2 2 2 2 2 2 2 2 2 ...
## $ LOCUS : num 0.29 -0.42 0.71 0.06 0.22 0.46 0.44 0.68 0.06 0.05 ...
## $ CONCPT: num 0.88 0.03 0.03 0.03 -0.28 0.03 -0.47 0.25 0.56 0.15 ...
## $ MOT : num 0.67 0.33 0.67 0 0 0 0.33 1 0.33 1 ...
## $ RDG : num 33.6 46.9 41.6 38.9 36.3 49.5 62.7 44.2 46.9 44.2 ...
## $ WRTG : num 43.7 35.9 59.3 41.1 48.9 46.3 64.5 51.5 41.1 49.5 ...
## $ MATH : num 40.2 41.9 41.9 32.7 39.5 46.2 48 36.9 45.3 40.5 ...
## $ SCI : num 39 36.3 44.4 41.7 41.7 41.7 63.4 49.8 47.1 39 ...
## $ CIV : num 40.6 45.6 45.6 40.6 45.6 35.6 55.6 55.6 55.6 50.6 ...
opcional(si desea ver entonces summary…)
summary(A)
## ID SEX RACE SES SCTYP
## 1 : 1 HOMBRE:327 ASIATICO: 71 ALTO :139 PRIVADA: 94
## 2 : 1 MUJER :273 BLANCO : 34 BAJO :162 PUBLICA:506
## 3 : 1 HISPANO :437 MEDIO:299
## 4 : 1 NEGRO : 58
## 5 : 1
## 6 : 1
## (Other):594
## LOCUS CONCPT MOT RDG
## Min. :-2.23000 Min. :-2.620000 Min. :0.0000 Min. :28.3
## 1st Qu.:-0.37250 1st Qu.:-0.300000 1st Qu.:0.3300 1st Qu.:44.2
## Median : 0.21000 Median : 0.030000 Median :0.6700 Median :52.1
## Mean : 0.09653 Mean : 0.004917 Mean :0.6608 Mean :51.9
## 3rd Qu.: 0.51000 3rd Qu.: 0.440000 3rd Qu.:1.0000 3rd Qu.:60.1
## Max. : 1.36000 Max. : 1.190000 Max. :1.0000 Max. :76.0
##
## WRTG MATH SCI CIV
## Min. :25.50 Min. :31.80 Min. :26.00 Min. :25.70
## 1st Qu.:44.30 1st Qu.:44.50 1st Qu.:44.40 1st Qu.:45.60
## Median :54.10 Median :51.30 Median :52.60 Median :50.60
## Mean :52.38 Mean :51.85 Mean :51.76 Mean :52.05
## 3rd Qu.:59.90 3rd Qu.:58.38 3rd Qu.:58.65 3rd Qu.:60.50
## Max. :67.10 Max. :75.50 Max. :74.20 Max. :70.50
##
#NO OLVIDAR!! SIEMPRE SI USAS TABLAS DESDE LA WEB ,DEBES DE VISUALIZAR LOS NOMBRES.(así utilices desde csv o tablas desde la web)
tablas desde la WEB:
library(htmltab)
A=htmltab(doc ="https://en.wikipedia.org/wiki/List_of_wars_by_death_toll",
which ='//*[@id="mw-content-text"]/div/table[4]')
#ojo:no olvides que el link general debe tener comillas de dos lineas ,mientras que el which debe tener comilla de 1 sola linea.
También debes recordar en el which va el copy xpath de toda la tabla pedida.Luego ya vas separando lo que te piden con los comandos ….
names(A)
## [1] "War" "Deathrange" "Geometricmean(Note 1)"
## [4] "Date" "Combatants" "Location"
## [7] "Notes"
#NO OLVIDAR!! SIEMPRE SI te piden QUEDARTE SOLO CON 2 O 3 ,DEBES DE VISUALIZAR LOS NOMBRES!!(así utilices desde csv o tablas desde la web)… porque
AA = htmltab(doc ="https://en.wikipedia.org/wiki/List_of_wars_by_death_toll" ,
which ='//*[@id="mw-content-text"]/div/table[6]')
## Warning: Columns [Notes] seem to have no data and are removed. Use
## rm_nodata_cols = F to suppress this behavior
names(AA)
## [1] "War" "Deathrange" "Geometricmean" "Date"
## [5] "Combatants" "Location"
AAA = htmltab(doc = "https://en.wikipedia.org/wiki/List_of_wars_by_death_toll",
which ='//*[@id="mw-content-text"]/div/table[7]')
## Warning: Columns [Notes] seem to have no data and are removed. Use
## rm_nodata_cols = F to suppress this behavior
names(AAA)
## [1] "War" "Deathrange" "Geometricmean" "Date"
## [5] "Combatants" "Location"
#Quieres combinar los tres en uno solo. Eso se puede hacer si todas las columnas tienen nombres identicos. Entonces como vemos en los names solo se repiten war y location en las tres tablas.COLOCAMOS SOLO ESTO ;por ende, CREAMOS PARA CADA TABLA UN NUEVO NOMBRE (PARA CADA DATA). #OJO También se puede colocar elmismo nombbre de la data nueva y de la data antigua A=A[,c(“War”,“Location”)]
suerte=A[,c("War","Location")]
suertee=AA[,c("War","Location")]
suerteee=AAA[,c("War","Location")]
se crearon nuevos nombres porque ya son datas distintos que tiene war y location .Ahora agrupamos todos porque ya tienen COLUMNAS IDENTICAS.
#PARA AGRUPAR LAS 3 TABLAS ,UNA VEZ QUE TENGAN SUS COLUMNAS IDENTICAS, SE USA LA función RBIND!
felizsuerte=rbind(suerte,suertee,suerteee)
Feliz suerte es la nueva data creada .Ahí está las tres datas actualizadas ya que solo se pueden agrupar si tienen columnas identicas.
str(felizsuerte)
## 'data.frame': 162 obs. of 2 variables:
## $ War : chr "Conquests of Cyrus the Great" "Greco–Persian Wars" "Samnite Wars" "Wars of Alexander the Great" ...
## $ Location: chr "Middle East" "Greece" "Italy" "Middle East / North Africa / Central Asia / India" ...
ANALISIS ESTADISTICO—
table(felizsuerte$Location)
##
## Afghanistan
## 3
## Algeria
## 3
## Americas
## 1
## Angola
## 2
## Balkan Peninsula
## 1
## Bangladesh
## 1
## Bosnia
## 1
## British Isles
## 1
## Burundi
## 1
## Caucasus region
## 1
## Central Africa
## 2
## China
## 9
## China / Vietnam
## 1
## Colombia
## 3
## Congo
## 4
## Crimean Peninsula
## 1
## Cuba
## 2
## East Asia
## 1
## Eastern Europe
## 4
## Eastern Europe / Middle East / North Africa
## 1
## England
## 2
## England / Wales
## 1
## Ethiopia
## 2
## Eurasia
## 2
## Europe
## 4
## Europe / Americas
## 2
## Europe / Middle East ("Holy Land")
## 1
## Finland
## 1
## France
## 3
## Germany
## 1
## Greece
## 2
## Haiti
## 1
## Iberian Peninsula
## 1
## India
## 4
## India-Bangladesh
## 1
## Indonesia
## 1
## Iraq
## 5
## Italy
## 1
## Korea
## 3
## Laos
## 1
## Lebanon
## 1
## Libya
## 1
## Madagascar
## 1
## Manchuria
## 1
## Mexico
## 4
## Middle East
## 7
## Middle East / North Africa
## 1
## Middle East / North Africa / Central Asia / India
## 1
## Middle East / North Africa / Southern Europe
## 1
## Middle East/North Africa
## 1
## Mozambique
## 1
## Myanmar
## 1
## New Guinea
## 1
## Nigeria
## 2
## North Africa
## 1
## North America
## 1
## North India / Pakistan
## 1
## Northeast India
## 2
## Northern China
## 1
## Northern Europe
## 1
## Pakistan
## 1
## Patagonia
## 1
## Peru
## 2
## Philippines
## 3
## Russia
## 2
## Rwanda
## 1
## Scotland / England
## 1
## Sierra Leone
## 1
## Somalia
## 1
## South Africa
## 1
## South America
## 1
## Southeast Asia
## 2
## Southeast Europe
## 1
## Southern Africa
## 1
## Southern Europe
## 1
## Southern Europe / North Africa
## 2
## Spain
## 2
## Sri Lanka
## 1
## Sudan
## 3
## Syria
## 1
## Tunisia
## 1
## Uganda
## 1
## USA
## 1
## Venezuela
## 1
## Vietnam
## 1
## Western Europe
## 4
## Western Europe / North Africa
## 2
## Worldwide
## 7
## Yemen
## 2
library(knitr)
dataTable=table(felizsuerte$Location)
kable(dataTable)
| Var1 | Freq |
|---|---|
| Afghanistan | 3 |
| Algeria | 3 |
| Americas | 1 |
| Angola | 2 |
| Balkan Peninsula | 1 |
| Bangladesh | 1 |
| Bosnia | 1 |
| British Isles | 1 |
| Burundi | 1 |
| Caucasus region | 1 |
| Central Africa | 2 |
| China | 9 |
| China / Vietnam | 1 |
| Colombia | 3 |
| Congo | 4 |
| Crimean Peninsula | 1 |
| Cuba | 2 |
| East Asia | 1 |
| Eastern Europe | 4 |
| Eastern Europe / Middle East / North Africa | 1 |
| England | 2 |
| England / Wales | 1 |
| Ethiopia | 2 |
| Eurasia | 2 |
| Europe | 4 |
| Europe / Americas | 2 |
| Europe / Middle East (“Holy Land”) | 1 |
| Finland | 1 |
| France | 3 |
| Germany | 1 |
| Greece | 2 |
| Haiti | 1 |
| Iberian Peninsula | 1 |
| India | 4 |
| India-Bangladesh | 1 |
| Indonesia | 1 |
| Iraq | 5 |
| Italy | 1 |
| Korea | 3 |
| Laos | 1 |
| Lebanon | 1 |
| Libya | 1 |
| Madagascar | 1 |
| Manchuria | 1 |
| Mexico | 4 |
| Middle East | 7 |
| Middle East / North Africa | 1 |
| Middle East / North Africa / Central Asia / India | 1 |
| Middle East / North Africa / Southern Europe | 1 |
| Middle East/North Africa | 1 |
| Mozambique | 1 |
| Myanmar | 1 |
| New Guinea | 1 |
| Nigeria | 2 |
| North Africa | 1 |
| North America | 1 |
| North India / Pakistan | 1 |
| Northeast India | 2 |
| Northern China | 1 |
| Northern Europe | 1 |
| Pakistan | 1 |
| Patagonia | 1 |
| Peru | 2 |
| Philippines | 3 |
| Russia | 2 |
| Rwanda | 1 |
| Scotland / England | 1 |
| Sierra Leone | 1 |
| Somalia | 1 |
| South Africa | 1 |
| South America | 1 |
| Southeast Asia | 2 |
| Southeast Europe | 1 |
| Southern Africa | 1 |
| Southern Europe | 1 |
| Southern Europe / North Africa | 2 |
| Spain | 2 |
| Sri Lanka | 1 |
| Sudan | 3 |
| Syria | 1 |
| Tunisia | 1 |
| Uganda | 1 |
| USA | 1 |
| Venezuela | 1 |
| Vietnam | 1 |
| Western Europe | 4 |
| Western Europe / North Africa | 2 |
| Worldwide | 7 |
| Yemen | 2 |
GRÁFICO—–
library(ggplot2)
base = ggplot(data=felizsuerte,aes(x=Location))
bar1 = base + geom_bar()
bar1
bar1 = bar1 + labs(x=“Pais/zona”, y=“Cantidad”, title=“Ubicacion de las Guerras en la historia”, subtitle = “Solo con mas 25000 muertos”, caption = “Fuente: Wikipedia”)
bar1
EstadísticoS——– 1.CENTRALES:MODA ojo:en este caso ,SOLO TIENE MODA YA QUE ES UNA VARIABLE NOMINAL(LOCATION).
library(DescTools)
Mode(felizsuerte$Location)
## [1] "China"
## attr(,"freq")
## [1] 9
2.Dispersión Concentracion: Herfindahl- Hirschman
< 0.01 : indica que la moda no es significativa, las categorias tienen pesos similares. < 0.15 : indica que la moda no es significativa, varias categorias tienen pesos similares. entre 0.15 - 0.25: hay una moda. 0.25: La moda se diferencia de los demas
library(DescTools)
Herfindahl(dataTable)
## [1] 0.01851852
Representatividad Efectiva:Laakso-Taagepera.
1/Herfindahl(dataTable)
## [1] 54
Hay 54 locaciones importantes de 89.
EXPLORACIÓN ORDINAL: realizar:Quédate con los scores para el 2016, y claro, Country y Region
Adata = htmltab(doc = "https://www.nationsonline.org/oneworld/corruption.htm",
which ='/html/body/table[3]')
## Neither <thead> nor <th> information found. Taking first table row for the header. If incorrect, specifiy header argument.
## Warning: Columns [ ] seem to have no data and are removed. Use
## rm_nodata_cols = F to suppress this behavior
names(Adata)
## [1] "Rank" "Country" "2016 Score" "2015 Score" "2014 Score"
## [6] "2013 Score" "2012 Score" "Region"
corruptionnuevo=Adata[,c(2,3,8)]
names(corruptionnuevo)
## [1] "Country" "2016 Score" "Region"
#evitar espacio en el nombre de la COLUMNA:2016 score.
names(corruptionnuevo)[2]="score2016"
str(corruptionnuevo)
## 'data.frame': 177 obs. of 3 variables:
## $ Country : chr "Denmark" "New Zealand" "Finland" "Sweden" ...
## $ score2016: chr "90" "90" "89" "88" ...
## $ Region : chr "Europe" "Asia Pacific" "Europe" "Europe" ...
FORMATEAR O RECODIFICAR:
corruptionnuevo[,c(1,3)]=lapply(corruptionnuevo[,c(1,3)], as.factor)
ojo:PARA cambiar a más de 2 VARIABLEs NUMéRICAs corruptionnuevo[,c(1,2)]=lapply(corruptionnuevo[,c(1,2)], as.numeric)
corruptionnuevo$score2016=as.numeric(corruptionnuevo$score2016)
## Warning: NAs introduced by coercion
El cambio ha producido NA (valores perdidos), eso sucede pues R encontró un valor no numerico. Veamos cual es esa fila:
corruptionnuevo[!complete.cases(corruptionnuevo$score2016),]
## Country score2016
## 178 To get in-depth information visit:Transparency International NA
## Region
## 178 To get in-depth information visit:Transparency International
Se verifica que esa fila no tenia informacion de un pais, era solo una referencia (visita la web original). nos quedamos sin esa fila:
corruption=corruption[complete.cases(corruption$score2016),]
EXPLORACION VARIABLES CATEGORICAS:————- http://rpubs.com/EstadisticaCP_unmsm/537279 Tabla # simple exploración con función table: table(sere19\(MODALIDAD) tabla de frecuencias: V.CATEGORICAS NOMINAL(MODA). tabla de frecuencias: Grafico de barras. grafico de pareto. ESTADISTICO O MEDIDAS DE TENDENCIA CENTRAL:MODA. Concentracion: Herfindahl- Hirschman. Representatividad Efectiva : Laakso - Taagepera. V.CATEGORICAS ORDINAL(MEDIANA). table. OrdDf.Tabla de frecuencias. Grafico de barras. grafico de pareto. ESTADISTICO O MEDIDAS DE TENDENCIA CENTRAL: MODA....library(DescTools) Mode(A\)DÍA) MEDIANA …Median(A\(DÍA). Concentracion: Herfindahl- Hirschman. Representatividad Efectiva : Laakso - Taagepera. al tener mediana se puede hacer aquí tbn BOXPLOT: ggplot(A,aes(y=DÍA)) + geom_boxplot() +scale_y_discrete(limits=OrdDf\)variable)
EXPLORACIÓN VARIABLES NUMÉRICAS:——————
link2='https://docs.google.com/spreadsheets/d/e/2PACX-1vTgDnZeJUe5Qdn-Il3Ob1u630GIYyxf5nomPu3oqrb5L31vUYCHsrtA0_tl2gEQ82mOI7-l1B9TtyZo/pub?gid=753961441&single=true&output=csv'
B=read.csv('https://docs.google.com/spreadsheets/d/e/2PACX-1vTgDnZeJUe5Qdn-Il3Ob1u630GIYyxf5nomPu3oqrb5L31vUYCHsrtA0_tl2gEQ82mOI7-l1B9TtyZo/pub?gid=753961441&single=true&output=csv', stringsAsFactors = F)
str(B)
## 'data.frame': 33 obs. of 4 variables:
## $ EMPRESA : chr "Ananea" "Antamina" "Ares" "Argentum" ...
## $ Responsable: chr "Contrata" "Empresa" "Empresa" "Contrata" ...
## $ Tama : chr "Pequeña" "Grande" "Mediana" "Mediana" ...
## $ accidentes : int 20 5 10 6 5 19 5 23 6 16 ...
B[,c(1:3)]=lapply(B[,c(1:3)], as.factor)
Parte 1. EXPLORACIÓN GRÁFICAA—————————— #histograma . library(ggplot2)…
library(ggplot2)
base1=ggplot(B,aes(x=accidentes))
histNum= base1 + geom_histogram(bins=7)
histNum
La exploración numérica nos debe sugerir:
Si la media es representativo o no. Si hay asimetría, y hacia donde se concentran los datos. Si hay valores atípicos.
Los atípicos se ven claramente en un boxplot
base2=ggplot(B,aes(y=accidentes))
box=base2 + geom_boxplot() + coord_flip()
box
sÍ HAY atípicos.
Para ser más preciso en nuestra exploración, debemos calcular diversos indicadores estadísticos.
summary(B$accidentes)
## Min. 1st Qu. Median Mean 3rd Qu. Max.
## 5.00 5.00 8.00 10.76 13.00 42.00
ESTO LO VEREMOS EN EL BOXPLOT:
library(ggplot2)
estadigrafos=round(as.vector(summary(B$accidentes)),2)
box + scale_y_continuous(breaks = estadigrafos)
SE COMPRUEBA QUE HAY ASIMETRIA .Uns asimetria postiva. Entonces la media es mayor que la mediana.
Si la media es mayor que la mediana la asimetría tiende a ser positiva (cola a la derecha). Hay tendencia a la asimetría negativa (cola a la izquierda) cuando la mediana es mayor que la media. Aquí se nota claramente que hay asimetría, pero podemos confirmarla calculando el coeficiente respectivo:
#Calcular el coeficiente:
library(DescTools)
Skew(B$accidentes,conf.level = 0.05)
## skew lwr.ci upr.ci
## 2.251112 2.550799 2.613701
IQR(B$accidentes)
## [1] 8
el primer y tercer cuartil hay sólo 8 valores; asi, el 50%
q3=as.numeric(summary(B$accidentes)[5])
#Calculadno el umbral o la distancia del Q3
umbral= q3+1.5*IQR(B$accidentes)
umbral
## [1] 25
#GINI
Gini(B$accidentes,conf.level=0.95)
## Warning in norm.inter(t, adj.alpha): extreme order statistics used as
## endpoints
## gini lwr.ci upr.ci
## 0.3362676 0.2710883 0.4316955
el Gini es 0, TODAS LA EMPRESAS causan la MISMA cantidad de accidentes; si fuera 1, 1 SOLA EMPRESA causa todos los accidentes. curva de Lorenz
library(gglorenz)
## Registered S3 methods overwritten by 'ineq':
## method from
## plot.Lc DescTools
## lines.Lc DescTools
base1 + gglorenz::stat_lorenz(color='red') +
geom_abline(linetype = "dashed") + coord_fixed() +
labs(x = "% Empresas ordenadas por accidentes causados",
y = "% Acumulado de Accidentes",
title = "Relación empresa / accidente",
caption = "Fuente: MINEM")
DISTRIBUCIÓN: se acerca a la diagonal, hay igualdad de distribución. cada empresa contribuye con la misma cantidad de accidentes (Gini = 0).
en este caso…No se acerca A LA DIAGONAL,NO HAY IGUALDAD DE DISTRIBUCIÓN.
EXPLORACION NUMERICA .(aNA mARIA.) formateo : pbinominal\(PBInominal=gsub(",","",pbinominal\)PBInominal) #cambiamos las comas por nada pbinominal\(PBInominal=as.numeric(pbinominal\)PBInominal
Graficos #Histograma #Boxplot o diagrama de cajas #Estadígrafos #1.summary(pbinominal$PBInominal)(ahí veras los cuartiles etc) #2.De nuevo BOXPLOT:media es mayor a la mediana, eso significa que se tiene una asimetría positiva. #Distancia/umbral intercuartilica. #GINI #LORENTZ
library(htmltab)
A = htmltab(doc ="https://www.nationsonline.org/oneworld/corruption.htm",
which ='/html/body/table[3]')
## Neither <thead> nor <th> information found. Taking first table row for the header. If incorrect, specifiy header argument.
## Warning: Columns [ ] seem to have no data and are removed. Use
## rm_nodata_cols = F to suppress this behavior
str(A)
## 'data.frame': 177 obs. of 8 variables:
## $ Rank : chr "1" "1" "3" "4" ...
## $ Country : chr "Denmark" "New Zealand" "Finland" "Sweden" ...
## $ 2016 Score: chr "90" "90" "89" "88" ...
## $ 2015 Score: chr "91" "88" "90" "89" ...
## $ 2014 Score: chr "92" "91" "89" "87" ...
## $ 2013 Score: chr "91" "91" "89" "89" ...
## $ 2012 Score: chr "90" "90" "90" "88" ...
## $ Region : chr "Europe" "Asia Pacific" "Europe" "Europe" ...
Quédate con los scores para el 2016, y claro, Country y Region:
names(A)
## [1] "Rank" "Country" "2016 Score" "2015 Score" "2014 Score"
## [6] "2013 Score" "2012 Score" "Region"
nuevoA=A[c(2,3,8)]
str(nuevoA)
## 'data.frame': 177 obs. of 3 variables:
## $ Country : chr "Denmark" "New Zealand" "Finland" "Sweden" ...
## $ 2016 Score: chr "90" "90" "89" "88" ...
## $ Region : chr "Europe" "Asia Pacific" "Europe" "Europe" ...
cambiar 2016 score
names(nuevoA)[2]="score2016"
str(nuevoA)
## 'data.frame': 177 obs. of 3 variables:
## $ Country : chr "Denmark" "New Zealand" "Finland" "Sweden" ...
## $ score2016: chr "90" "90" "89" "88" ...
## $ Region : chr "Europe" "Asia Pacific" "Europe" "Europe" ...
FORMATEAR: NO OLVIDAR!!!!!!!! DEBES DE FORMATEAR CON EL nuevoA
nuevoA$score2016=as.numeric(nuevoA$score2016)
## Warning: NAs introduced by coercion
Nas NO DEBE SALIR.Entonces…
nuevoA[!complete.cases(nuevoA$score2016),]
## Country score2016
## 178 To get in-depth information visit:Transparency International NA
## Region
## 178 To get in-depth information visit:Transparency International
eliminamos esa fila uwu
nuevoA=nuevoA[complete.cases(nuevoA$score2016),]
nuevoA$Region=as.factor(nuevoA$Region)
OJO:SOLO REGION ES V.NOMINAL POR ESO HACES EL AS.FACTOR COUNTRY NO SE PUEDE CLASIFICAR(los nombres de los paises NO SE PUEDEN CLASIFICAR) entonces mantienes en AS.CHARACTER.(as.character es para elementos que no se pueden clasificar)
str(nuevoA)
## 'data.frame': 176 obs. of 3 variables:
## $ Country : chr "Denmark" "New Zealand" "Finland" "Sweden" ...
## $ score2016: num 90 90 89 88 86 85 84 83 82 81 ...
## $ Region : Factor w/ 22 levels "Americas","Asia",..: 8 3 8 8 8 8 13 8 1 8 ...
LISTOOOOOOOOO :) WIIIII
A=read.csv("https://docs.google.com/spreadsheets/d/e/2PACX-1vTFp8tPWkUD3qMcuXsqySAHJUZBoIjiFb_pyIJfTiQAK070YNo8G__7wOD_nl_UPYdWnMbW7I5VbRxr/pub?gid=477181888&single=true&output=csv", stringsAsFactors = F,na.strings = '')
str(A)
## 'data.frame': 600 obs. of 13 variables:
## $ ID : int 1 2 3 4 5 6 7 8 9 10 ...
## $ SEX : chr "HOMBRE" "MUJER" "HOMBRE" "HOMBRE" ...
## $ RACE : chr "ASIATICO" "ASIATICO" "ASIATICO" "ASIATICO" ...
## $ SES : chr "ALTO" "ALTO" "ALTO" "MEDIO" ...
## $ SCTYP : chr "PUBLICA" "PUBLICA" "PUBLICA" "PUBLICA" ...
## $ LOCUS : num 0.29 -0.42 0.71 0.06 0.22 0.46 0.44 0.68 0.06 0.05 ...
## $ CONCPT: num 0.88 0.03 0.03 0.03 -0.28 0.03 -0.47 0.25 0.56 0.15 ...
## $ MOT : num 0.67 0.33 0.67 0 0 0 0.33 1 0.33 1 ...
## $ RDG : num 33.6 46.9 41.6 38.9 36.3 49.5 62.7 44.2 46.9 44.2 ...
## $ WRTG : num 43.7 35.9 59.3 41.1 48.9 46.3 64.5 51.5 41.1 49.5 ...
## $ MATH : num 40.2 41.9 41.9 32.7 39.5 46.2 48 36.9 45.3 40.5 ...
## $ SCI : num 39 36.3 44.4 41.7 41.7 41.7 63.4 49.8 47.1 39 ...
## $ CIV : num 40.6 45.6 45.6 40.6 45.6 35.6 55.6 55.6 55.6 50.6 ...
formateamos:
A[,c(2,3,5)]=lapply(A[,c(2,3,5)],as.factor)
A$SES=as.ordered(A$SES)
str(A)
## 'data.frame': 600 obs. of 13 variables:
## $ ID : int 1 2 3 4 5 6 7 8 9 10 ...
## $ SEX : Factor w/ 2 levels "HOMBRE","MUJER": 1 2 1 1 1 2 2 1 2 1 ...
## $ RACE : Factor w/ 4 levels "ASIATICO","BLANCO",..: 1 1 1 1 1 1 1 1 1 1 ...
## $ SES : Ord.factor w/ 3 levels "ALTO"<"BAJO"<..: 1 1 1 3 3 3 1 1 3 1 ...
## $ SCTYP : Factor w/ 2 levels "PRIVADA","PUBLICA": 2 2 2 2 2 2 2 2 2 2 ...
## $ LOCUS : num 0.29 -0.42 0.71 0.06 0.22 0.46 0.44 0.68 0.06 0.05 ...
## $ CONCPT: num 0.88 0.03 0.03 0.03 -0.28 0.03 -0.47 0.25 0.56 0.15 ...
## $ MOT : num 0.67 0.33 0.67 0 0 0 0.33 1 0.33 1 ...
## $ RDG : num 33.6 46.9 41.6 38.9 36.3 49.5 62.7 44.2 46.9 44.2 ...
## $ WRTG : num 43.7 35.9 59.3 41.1 48.9 46.3 64.5 51.5 41.1 49.5 ...
## $ MATH : num 40.2 41.9 41.9 32.7 39.5 46.2 48 36.9 45.3 40.5 ...
## $ SCI : num 39 36.3 44.4 41.7 41.7 41.7 63.4 49.8 47.1 39 ...
## $ CIV : num 40.6 45.6 45.6 40.6 45.6 35.6 55.6 55.6 55.6 50.6 ...
exploración BIVARIADA——————
link="https://docs.google.com/spreadsheets/d/e/2PACX-1vQ_VNceU6ncsQs-_KFvkQsv2XqYKRCMyRYCDYQFosH5bo6Yt-l1gE8ZRdP44m4Rh8lQB2nOY-Y-p0ZP/pub?gid=0&single=true&output=csv"
A=read.csv("https://docs.google.com/spreadsheets/d/e/2PACX-1vQ_VNceU6ncsQs-_KFvkQsv2XqYKRCMyRYCDYQFosH5bo6Yt-l1gE8ZRdP44m4Rh8lQB2nOY-Y-p0ZP/pub?gid=0&single=true&output=csv", stringsAsFactors = F)
str(A)
## 'data.frame': 600 obs. of 15 variables:
## $ ID : int 1 2 3 4 5 6 7 8 9 10 ...
## $ SEX : int 2 1 2 2 2 1 1 2 1 2 ...
## $ RACE : int 2 2 2 2 2 2 2 2 2 2 ...
## $ SES : int 1 1 1 2 2 2 1 1 2 1 ...
## $ SCTYP : int 1 1 1 1 1 1 1 1 1 1 ...
## $ HSP : int 3 2 2 3 3 2 1 1 1 1 ...
## $ LOCUS : num 0.29 -0.42 0.71 0.06 0.22 0.46 0.44 0.68 0.06 0.05 ...
## $ CONCPT: num 0.88 0.03 0.03 0.03 -0.28 0.03 -0.47 0.25 0.56 0.15 ...
## $ MOT : num 0.67 0.33 0.67 0 0 0 0.33 1 0.33 1 ...
## $ CAR : int 10 2 9 15 1 11 10 9 9 11 ...
## $ RDG : num 33.6 46.9 41.6 38.9 36.3 49.5 62.7 44.2 46.9 44.2 ...
## $ WRTG : num 43.7 35.9 59.3 41.1 48.9 46.3 64.5 51.5 41.1 49.5 ...
## $ MATH : num 40.2 41.9 41.9 32.7 39.5 46.2 48 36.9 45.3 40.5 ...
## $ SCI : num 39 36.3 44.4 41.7 41.7 41.7 63.4 49.8 47.1 39 ...
## $ CIV : num 40.6 45.6 45.6 40.6 45.6 35.6 55.6 55.6 55.6 50.6 ...
A\(ID=as.character (A\)ID) A[,c(2,3,5,6,7)]=lapply(A[,c(2,3,5,6,7)],as.factor)
A\(SES=as.ordered(A\)SES)
hsb\(ID=as.character(hsb\)ID)
hsb[,c(2,3,5,6,10)]=lapply(hsb[,c(2,3,5,6,10)],as.factor)
hsb\(HSP=as.ordered(hsb\)HSP)
EXPLORACIÓN BIVARIADA PARTE 1————————— #nota. recuerda que así tengas la tabla desde excel o desde la web debes de FORMATEAR. #EN ALGUNOS CASOS EL FORMATEO NO ES TAN OBVIO.EJEMPLO: en los chr de sex o race supones que es as.factor pero YA NO APARECEN TEXTO SINO NUMEROS.Entoces OBSERVAR LA METADATA y apartir de ahí FORMATEAR. SE TRABAJA CON V.D y NUMERICA saber la hipótesis nula de la prueba estadística.
test de normalidad:SHAPIRO WILK ho: la variable se distribuye normalmente. si hay normalidad se usarán técnicas paramétricas, si no la hay, las NO paramétricas. PREGUNTAS!!!!!! PREGUNTA 1.Analizar MATH y SEX.escribir conclusiones numerico ,categórico
link="https://docs.google.com/spreadsheets/d/e/2PACX-1vQ_VNceU6ncsQs-_KFvkQsv2XqYKRCMyRYCDYQFosH5bo6Yt-l1gE8ZRdP44m4Rh8lQB2nOY-Y-p0ZP/pub?gid=0&single=true&output=csv"
hsb=read.csv(link, stringsAsFactors = F)
f1=formula(MATH ~ SEX)
aggregate(f1, hsb,mean)
## SEX MATH
## 1 1 52.34542
## 2 2 51.43456
library(ggpubr)
## Loading required package: magrittr
## Loading required package: magrittr
ggqqplot(data=hsb,x="MATH") + facet_grid(. ~ SEX)
(esto es opcional) TEST DE NROMALIDAD:SHAPIRO WILK