Funciones: En R tenemos distintas funciones, por ejemplo:
# Suma
9+20
## [1] 29
# Resta
37-8
## [1] 29
# Multiplicación
25*4
## [1] 100
# División
99/3
## [1] 33
# Potencia
5**3
## [1] 125
Módulos y librerias principales: En R, no hay una estructura modular predeterminada como en otros lenguajes de programación, pero existen una serie de paquetes y bibliotecas que se consideran fundamentales y comúnmente utilizados para una amplia gama de tareas. Estos paquetes proporcionan funciones y herramientas para realizar análisis de datos, visualizaciones, manipulación de datos y más. Algunos de los paquetes principales en R son:
Asignación: la asignación de variables se realiza utilizando el operador “<-” o el operador “=” A contuacion tenemos algunos ejemplos:
# Asignación de un número a una variable
x <- 10
print(x)
## [1] 10
# Asignación de un texto a una variable
mensaje <- "Hola, mundo!"
print(mensaje)
## [1] "Hola, mundo!"
# Asignación de un vector a una variable
valores <- c(2, 4, 6, 8, 10)
print(valores)
## [1] 2 4 6 8 10
# Asignación de un resultado de operación a una variable
suma <- 3 + 7
print(suma)
## [1] 10
Tipos de datos en R:
En R, los tipos de datos para números enteros, números de punto flotante y cadenas de texto se representan de la siguiente manera:
Enteros (integer):
Los números enteros en R se representan utilizando el tipo de dato “integer” Puedes crear números enteros directamente o convertir otros tipos de datos a enteros utilizando la función “as.integer()”
num_entero <- 5L # La "L" al final indica que es un entero
class(num_entero)
## [1] "integer"
Reales o decimales (numeric):
Los números de punto flotante, que representan números reales o decimales, se manejan por defecto en R y se representan con el tipo de dato “numeric” o “double”
# Crear un número de punto flotante
num_decimal <- 3.14
class(num_decimal)
## [1] "numeric"
Cadenas de texto (character): Las cadenas de texto en R se representan utilizando el tipo de dato character. Puedes crear cadenas de texto utilizando comillas simples (’ ’) o comillas dobles (” “)
# Crear una cadena de texto
texto <- "Hola, mundo!"
class(texto)
## [1] "character"
Operadores de comparación:
En R, los operadores de comparación se utilizan para comparar valores y devolver un resultado lógico (TRUE o FALSE) según si la comparación es verdadera o falsa.
Igualdad y Desigualdad:
Igual a: “==” Devuelve TRUE si los valores son iguales.
x <- 5
y <- 10
# Igualdad
x == y
## [1] FALSE
x <- 5
y <- 5
# Igualdad
x == y
## [1] TRUE
Desigual a: “!=” Devuelve TRUE si los valores son diferentes.
x <- 5
y <- 10
# Desigualdad
x != y
## [1] TRUE
x <- 5
y <- 5
# Desigualdad
x != y
## [1] FALSE
Relacionales:
Mayor que: “>” Devuelve TRUE si el valor de la izquierda es mayor que el de la derecha.
# Mayor que
x <- 6
y <- 5
x > y
## [1] TRUE
Mayor o igual que: “>=” Devuelve TRUE si el valor de la izquierda es mayor o igual que el de la derecha.
x <- 5
y <- 5
# Mayor o igual que
x >= 5
## [1] TRUE
Menor que: “<” Devuelve TRUE si el valor de la izquierda es menor que el de la derecha.
x <- 6
y <- 5
# Menor que
x < y
## [1] FALSE
Menor o igual que: “<=” Devuelve TRUE si el valor de la izquierda es menor o igual que el de la derecha.
x <- 6
y <- 5
# Menor o igual que
y <= 10
## [1] TRUE
Para crear un DataFrame en R a partir de datos alojados en un enlace web, podemos utilizar funciones como “read.csv()” o “read.table()” para importar datos de archivos CSV o tabulares directamente desde una URL.
# Importar datos desde una URL y crear un DataFrame
url <- "https://raw.githubusercontent.com/tomwhite/covid-19-uk-data/ddcd5878047dafa89a8e2169c64def490cfa87ea/data/raw/phw/csv/Age_and_sex_distribution.csv"
data_frame <- read.csv(url)
# Mostrar las primeras filas del DataFrame importado
head(data_frame)
## Age.group Sex Cases Testing.episodes
## 1 <10 Male 1748 47091
## 2 <10 Female 1626 41402
## 3 <10 Unknown 0 114
## 4 10-19 Male 4618 43496
## 5 10-19 Female 5334 46995
## 6 10-19 Unknown 70 218
Cambiar nombres de columnas:
library(readr)
## Warning: package 'readr' was built under R version 4.3.2
# URL del archivo CSV
url <- "https://raw.githubusercontent.com/tomwhite/covid-19-uk-data/ddcd5878047dafa89a8e2169c64def490cfa87ea/data/raw/phw/csv/Age_and_sex_distribution.csv"
# Cargar el archivo CSV desde la URL
datos <- read_csv(url)
## Rows: 36 Columns: 4
## ── Column specification ────────────────────────────────────────────────────────
## Delimiter: ","
## chr (2): Age group, Sex
## dbl (2): Cases, Testing episodes
##
## ℹ 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.
# Ver los nombres actuales de las columnas
colnames(datos)
## [1] "Age group" "Sex" "Cases" "Testing episodes"
# Asignar nuevos nombres a las columnas
nuevos_nombres <- c("Edades", "Genero", "Positivo", "Testeados") # Lista de nuevos nombres
colnames(datos) <- nuevos_nombres
# Verificar los nombres actualizados de las columnas
colnames(datos)
## [1] "Edades" "Genero" "Positivo" "Testeados"
library(readr)
# URL del archivo CSV
url <- "https://raw.githubusercontent.com/tomwhite/covid-19-uk-data/ddcd5878047dafa89a8e2169c64def490cfa87ea/data/raw/phw/csv/Age_and_sex_distribution.csv"
# Cargar el archivo CSV desde la URL
datos <- read_csv(url)
## Rows: 36 Columns: 4
## ── Column specification ────────────────────────────────────────────────────────
## Delimiter: ","
## chr (2): Age group, Sex
## dbl (2): Cases, Testing episodes
##
## ℹ 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.
# Resumen estadístico de las variables
summary(datos)
## Age group Sex Cases Testing episodes
## Length:36 Length:36 Min. : 0.00 Min. : 4.0
## Class :character Class :character 1st Qu.: 8.75 1st Qu.: 171.2
## Mode :character Mode :character Median :1517.00 Median : 18629.0
## Mean :2666.61 Mean : 28858.9
## 3rd Qu.:4797.00 3rd Qu.: 47886.5
## Max. :9880.00 Max. :109132.0
En R el flujo del proceso de analisis de datos implica la recopilación de datos, limpieza, análisis estadístico y visualización para sacar conclusiones significativas para convertir datos en información útil
# Descargar el archivo desde el enlace
url <- "https://raw.githubusercontent.com/KT-1000/tuberculo-csv/master/data/TB_data_dictionary_2017-01-12.csv"
destino <- "archivo.csv" # Nombre del archivo en el que se guardará localmente
download.file(url, destino, method = "auto")
# Leer el archivo descargado
datos <- read.csv(destino)
# Realizar operaciones con los datos
head(datos) # Mostrar las primeras filas como ejemplo
## variable_name dataset code_list
## 1 bmu Community engagement
## 2 bmu_community_impl Community engagement
## 3 bmu_ref_data Community engagement
## 4 bmu_rxsupport_data Community engagement
## 5 bmu_rxsupport_data_coh Community engagement
## 6 community_data_available Community engagement 0=No; 1=Yes
## definition
## 1 Number of TB Basic Management Units in the country
## 2 Number of TB Basic Management Units which implemented community-based referrals or any form of community treatment adherence support
## 3 Number of Basic Management Units with data on referrals by community health workers / community volunteers
## 4 Number of Basic Management Units with data on community treatment adherence support
## 5 Total number of patients who started TB treatment in the Basic Management Units with data on community treatment adherence support
## 6 Are data available on community-based referrals or any form of community treatment adherence support?
Limpieza de datos Podemos realizar la limpieza de datos en R utilizando el paquete ¨data.table¨, que es conocido por su eficiencia en manipulación de datos, especialmente para conjuntos de datos grandes:
library(data.table)
## Warning: package 'data.table' was built under R version 4.3.2
# Cargar los datos desde el enlace
url <- "https://raw.githubusercontent.com/KT-1000/tuberculo-csv/master/data/TB_data_dictionary_2017-01-12.csv"
datos <- fread(url)
# Realizar limpieza de datos con data.table
datos_limpio <- datos[complete.cases(datos), ] # Eliminar filas con valores faltantes
# Realizar otras operaciones de limpieza según sea necesario
# Por ejemplo:
# datos_limpio[, NuevaColumna := Columna1 + Columna2] # Crear una nueva columna sumando otras dos columnas
# Visualizar los primeros resultados del conjunto de datos limpios
head(datos_limpio)
## variable_name dataset code_list
## 1: bmu Community engagement
## 2: bmu_community_impl Community engagement
## 3: bmu_ref_data Community engagement
## 4: bmu_rxsupport_data Community engagement
## 5: bmu_rxsupport_data_coh Community engagement
## 6: community_data_available Community engagement 0=No; 1=Yes
## definition
## 1: Number of TB Basic Management Units in the country
## 2: Number of TB Basic Management Units which implemented community-based referrals or any form of community treatment adherence support
## 3: Number of Basic Management Units with data on referrals by community health workers / community volunteers
## 4: Number of Basic Management Units with data on community treatment adherence support
## 5: Total number of patients who started TB treatment in the Basic Management Units with data on community treatment adherence support
## 6: Are data available on community-based referrals or any form of community treatment adherence support?
En este ejemplo: ¨fread¨ de ¨data.table¨ se utiliza para cargar los datos desde el enlace. ¨complete.cases¨ elimina las filas que contienen valores faltantes (¨NA¨) en cualquier columna.
Análisis estadístico:
Para realizar un análisis estadístico con datos provenientes de un enlace en R, es necesario cargar los datos desde ese enlace y luego aplicar las funciones estadísticas deseadas. Utilicemos el paquete readr para cargar los datos desde un enlace y el paquete base de R para realizar un análisis estadístico simple:
library(readr)
# Cargar los datos desde el enlace
url <- "https://raw.githubusercontent.com/KT-1000/tuberculo-csv/master/data/TB_burden_countries_2017-01-12.csv"
datos <- read_csv(url)
## Rows: 3434 Columns: 74
## ── Column specification ────────────────────────────────────────────────────────
## Delimiter: ","
## chr (7): country, iso2, iso3, iso_numeric, g_whoregion, source_inc, source_...
## dbl (66): year, e_pop_num, e_inc_100k, e_inc_100k_lo, e_inc_100k_hi, e_inc_n...
## lgl (1): source_tbhiv
##
## ℹ 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.
# Realizar un análisis estadístico básico
summary(datos) # Resumen estadístico de las variables numéricas
## country iso2 iso3 iso_numeric
## Length:3434 Length:3434 Length:3434 Length:3434
## Class :character Class :character Class :character Class :character
## Mode :character Mode :character Mode :character Mode :character
##
##
##
##
## g_whoregion year e_pop_num e_inc_100k
## Length:3434 Min. :2000 Min. :1.129e+03 Min. : 0.0
## Class :character 1st Qu.:2004 1st Qu.:6.343e+05 1st Qu.: 13.0
## Mode :character Median :2008 Median :5.435e+06 Median : 51.0
## Mean :2008 Mean :3.123e+07 Mean : 128.6
## 3rd Qu.:2012 3rd Qu.:1.979e+07 3rd Qu.: 173.0
## Max. :2015 Max. :1.376e+09 Max. :1354.0
##
## e_inc_100k_lo e_inc_100k_hi e_inc_num e_inc_num_lo
## Min. : 0.33 Min. : 0.45 Min. : 0 Min. : 0
## 1st Qu.: 13.00 1st Qu.: 17.00 1st Qu.: 220 1st Qu.: 220
## Median : 42.00 Median : 65.00 Median : 2900 Median : 2700
## Mean : 92.61 Mean : 178.50 Mean : 49988 Mean : 33267
## 3rd Qu.:123.00 3rd Qu.: 230.00 3rd Qu.: 17000 3rd Qu.: 13000
## Max. :885.00 Max. :1934.00 Max. :3190000 Max. :1650000
## NA's :80 NA's :80 NA's :80
## e_inc_num_hi source_inc e_inc_num_f014 e_inc_num_f014_lo
## Min. : 0 Length:3434 Min. : 0 Min. : 0
## 1st Qu.: 340 Class :character 1st Qu.: 4 1st Qu.: 1
## Median : 4100 Mode :character Median : 100 Median : 52
## Mean : 73561 Mean : 2221 Mean : 1119
## 3rd Qu.: 23000 3rd Qu.: 730 3rd Qu.: 380
## Max. :5220000 Max. :136000 Max. :78000
## NA's :80 NA's :3217 NA's :3217
## e_inc_num_f014_hi e_inc_num_f15plus e_inc_num_f15plus_lo e_inc_num_f15plus_hi
## Min. : 0 Min. : 0 Min. : 0 Min. : 0
## 1st Qu.: 9 1st Qu.: 58 1st Qu.: 37 1st Qu.: 80
## Median : 150 Median : 890 Median : 440 Median : 1300
## Mean : 3326 Mean : 16046 Mean : 6749 Mean : 25328
## 3rd Qu.: 1200 3rd Qu.: 5600 3rd Qu.: 2700 3rd Qu.: 8200
## Max. :193000 Max. :860000 Max. :194000 Max. :1610000
## NA's :3217 NA's :3217 NA's :3217 NA's :3217
## e_inc_num_f e_inc_num_f_lo e_inc_num_f_hi e_inc_num_m014
## Min. : 0 Min. : 0 Min. : 0 Min. : 0
## 1st Qu.: 75 1st Qu.: 47 1st Qu.: 98 1st Qu.: 2
## Median : 1000 Median : 530 Median : 1500 Median : 85
## Mean : 18268 Mean : 7887 Mean : 28645 Mean : 2192
## 3rd Qu.: 6300 3rd Qu.: 3000 3rd Qu.: 8900 3rd Qu.: 810
## Max. :995000 Max. :210000 Max. :1800000 Max. :119000
## NA's :3217 NA's :3217 NA's :3217 NA's :3217
## e_inc_num_m014_lo e_inc_num_m014_hi e_inc_num_m15plus e_inc_num_m15plus_lo
## Min. : 0 Min. : 0 Min. : 0 Min. : 0
## 1st Qu.: 1 1st Qu.: 2 1st Qu.: 120 1st Qu.: 93
## Median : 56 Median : 120 Median : 1600 Median : 1300
## Mean : 1373 Mean : 2998 Mean : 27446 Mean : 18939
## 3rd Qu.: 540 3rd Qu.: 1000 3rd Qu.: 8700 3rd Qu.: 6500
## Max. :78000 Max. :161000 Max. :1730000 Max. :1070000
## NA's :3217 NA's :3217 NA's :3217 NA's :3217
## e_inc_num_m15plus_hi e_inc_num_m e_inc_num_m_lo e_inc_num_m_hi
## Min. : 0 Min. : 0 Min. : 0 Min. : 0
## 1st Qu.: 150 1st Qu.: 130 1st Qu.: 99 1st Qu.: 170
## Median : 2100 Median : 1800 Median : 1400 Median : 2300
## Mean : 35935 Mean : 29664 Mean : 20316 Mean : 38921
## 3rd Qu.: 11000 3rd Qu.: 9400 3rd Qu.: 6900 3rd Qu.: 12000
## Max. :2380000 Max. :1850000 Max. :1150000 Max. :2540000
## NA's :3217 NA's :3217 NA's :3217 NA's :3217
## e_inc_num_014 e_inc_num_014_lo e_inc_num_014_hi e_inc_num_15plus
## Min. : 0 Min. : 0 Min. : 0 Min. : 0
## 1st Qu.: 10 1st Qu.: 8 1st Qu.: 13 1st Qu.: 180
## Median : 190 Median : 140 Median : 230 Median : 2400
## Mean : 4411 Mean : 3017 Mean : 5785 Mean : 43498
## 3rd Qu.: 1500 3rd Qu.: 1100 3rd Qu.: 2100 3rd Qu.: 14000
## Max. :255000 Max. :181000 Max. :328000 Max. :2590000
## NA's :3217 NA's :3217 NA's :3217 NA's :3217
## e_inc_num_15plus_lo e_inc_num_15plus_hi e_tbhiv_prct e_tbhiv_prct_lo
## Min. : 0 Min. : 0 Min. : 0.00 Min. : 0.00
## 1st Qu.: 160 1st Qu.: 200 1st Qu.: 1.20 1st Qu.: 0.92
## Median : 2200 Median : 2800 Median : 5.10 Median : 4.40
## Mean : 33440 Mean : 53507 Mean : 12.97 Mean : 11.08
## 3rd Qu.: 12000 3rd Qu.: 16000 3rd Qu.: 16.00 3rd Qu.: 14.00
## Max. :1750000 Max. :3420000 Max. :100.00 Max. :100.00
## NA's :3217 NA's :3217 NA's :579 NA's :589
## e_tbhiv_prct_hi e_inc_tbhiv_100k e_inc_tbhiv_100k_lo e_inc_tbhiv_100k_hi
## Min. : 0.01 Min. : 0.00 Min. : 0.000 Min. : 0.00
## 1st Qu.: 1.40 1st Qu.: 0.30 1st Qu.: 0.225 1st Qu.: 0.39
## Median : 6.00 Median : 2.20 Median : 1.700 Median : 2.90
## Mean : 14.71 Mean : 40.54 Mean : 25.754 Mean : 58.91
## 3rd Qu.: 18.00 3rd Qu.: 14.00 3rd Qu.: 8.800 3rd Qu.: 20.00
## Max. :100.00 Max. :1122.00 Max. :717.000 Max. :1615.00
## NA's :589 NA's :579 NA's :583 NA's :583
## e_inc_tbhiv_num e_inc_tbhiv_num_lo e_inc_tbhiv_num_hi source_tbhiv
## Min. : 0 Min. : 0 Min. : 0 Mode:logical
## 1st Qu.: 15 1st Qu.: 11 1st Qu.: 19 NA's:3434
## Median : 170 Median : 130 Median : 240
## Mean : 7866 Mean : 4782 Mean : 11782
## 3rd Qu.: 2000 3rd Qu.: 1300 3rd Qu.: 2800
## Max. :315000 Max. :202000 Max. :453000
## NA's :579 NA's :583 NA's :583
## e_mort_exc_tbhiv_100k e_mort_exc_tbhiv_100k_lo e_mort_exc_tbhiv_100k_hi
## Min. : 0.0000 Min. : 0.00 Min. : 0.00
## 1st Qu.: 0.9825 1st Qu.: 0.96 1st Qu.: 1.40
## Median : 4.2000 Median : 3.80 Median : 6.30
## Mean : 15.4137 Mean : 10.27 Mean : 23.62
## 3rd Qu.: 20.0000 3rd Qu.: 14.00 3rd Qu.: 30.00
## Max. :161.0000 Max. :117.00 Max. :264.00
## NA's :151 NA's :151
## e_mort_exc_tbhiv_num e_mort_exc_tbhiv_num_lo e_mort_exc_tbhiv_num_hi
## Min. : 0 Min. : 0 Min. : 0
## 1st Qu.: 17 1st Qu.: 19 1st Qu.: 27
## Median : 250 Median : 220 Median : 350
## Mean : 7230 Mean : 5410 Mean : 10257
## 3rd Qu.: 2000 3rd Qu.: 1400 3rd Qu.: 3200
## Max. :610000 Max. :530000 Max. :690000
## NA's :151 NA's :151
## e_mort_tbhiv_100k e_mort_tbhiv_100k_lo e_mort_tbhiv_100k_hi
## Min. : 0.00 Min. : 0.00 Min. : 0.00
## 1st Qu.: 0.01 1st Qu.: 0.00 1st Qu.: 0.16
## Median : 0.15 Median : 0.04 Median : 1.15
## Mean : 11.22 Mean : 7.80 Mean : 22.64
## 3rd Qu.: 2.40 3rd Qu.: 1.80 3rd Qu.: 7.90
## Max. :426.00 Max. :350.00 Max. :630.00
## NA's :606 NA's :606
## e_mort_tbhiv_num e_mort_tbhiv_num_lo e_mort_tbhiv_num_hi e_mort_100k
## Min. : 0.00 Min. : 0.00 Min. : 0.0 Min. : 0.00
## 1st Qu.: 0.14 1st Qu.: 0.01 1st Qu.: 8.6 1st Qu.: 1.00
## Median : 11.00 Median : 2.30 Median : 97.0 Median : 4.85
## Mean : 2378.64 Mean : 1816.25 Mean : 4413.1 Mean : 26.63
## 3rd Qu.: 307.50 3rd Qu.: 200.00 3rd Qu.: 1000.0 3rd Qu.: 24.00
## Max. :110000.00 Max. :91000.00 Max. :160000.0 Max. :492.00
## NA's :606 NA's :606
## e_mort_100k_lo e_mort_100k_hi e_mort_num e_mort_num_lo
## Min. : 0.00 Min. : 0.00 Min. : 0 Min. : 0
## 1st Qu.: 0.90 1st Qu.: 1.70 1st Qu.: 19 1st Qu.: 19
## Median : 4.00 Median : 7.35 Median : 270 Median : 220
## Mean : 18.24 Mean : 40.15 Mean : 9602 Mean : 7327
## 3rd Qu.: 17.00 3rd Qu.: 37.00 3rd Qu.: 2900 3rd Qu.: 2100
## Max. :411.00 Max. :687.00 Max. :710000 Max. :620000
## NA's :138 NA's :138 NA's :138
## e_mort_num_hi source_mort cfr cfr_lo
## Min. : 0 Length:3434 Min. :0.000 Min. :0.000
## 1st Qu.: 32 Class :character 1st Qu.:0.062 1st Qu.:0.040
## Median : 435 Mode :character Median :0.110 Median :0.070
## Mean : 13316 Mean :0.135 Mean :0.082
## 3rd Qu.: 4225 3rd Qu.:0.188 3rd Qu.:0.110
## Max. :810000 Max. :0.850 Max. :0.740
## NA's :138 NA's :3224 NA's :3224
## cfr_hi c_newinc_100k c_cdr c_cdr_lo
## Min. :0.000 Min. : 0.00 Min. : 0.00 Min. : 0.0
## 1st Qu.:0.100 1st Qu.: 12.00 1st Qu.: 61.00 1st Qu.: 43.0
## Median :0.155 Median : 40.00 Median : 80.00 Median : 64.0
## Mean :0.216 Mean : 77.96 Mean : 72.68 Mean : 59.7
## 3rd Qu.:0.318 3rd Qu.: 97.00 3rd Qu.: 87.00 3rd Qu.: 75.0
## Max. :0.990 Max. :855.00 Max. :290.00 Max. :210.0
## NA's :3224 NA's :164 NA's :240 NA's :240
## c_cdr_hi
## Min. : 0.0
## 1st Qu.: 89.0
## Median :100.0
## Mean : 91.1
## 3rd Qu.:100.0
## Max. :410.0
## NA's :240
# Calcular la media y la desviación estándar de una columna específica
media_columna <- mean(datos$year)
desviacion_columna <- sd(datos$year)
# Realizar un histograma de una columna
hist(datos$year)
CSV
# Cargar el archivo CSV desde el enlace directamente en un data frame
url <- "https://raw.githubusercontent.com/KT-1000/tuberculo-csv/master/data/TB_burden_countries_2017-01-12.csv"
datos <- read.csv(url)
# Verificar las primeras filas del data frame para asegurarse de que se importaron correctamente
head(datos)
## country iso2 iso3 iso_numeric g_whoregion year e_pop_num e_inc_100k
## 1 Afghanistan AF AFG 4 EMR 2000 19701940 190
## 2 Afghanistan AF AFG 4 EMR 2001 20531160 189
## 3 Afghanistan AF AFG 4 EMR 2002 21487079 189
## 4 Afghanistan AF AFG 4 EMR 2003 22507368 189
## 5 Afghanistan AF AFG 4 EMR 2004 23499850 189
## 6 Afghanistan AF AFG 4 EMR 2005 24399948 189
## e_inc_100k_lo e_inc_100k_hi e_inc_num e_inc_num_lo e_inc_num_hi
## 1 123 271 37000 24000 53000
## 2 123 271 39000 25000 56000
## 3 122 270 41000 26000 58000
## 4 122 270 43000 28000 61000
## 5 122 270 44000 29000 63000
## 6 122 270 46000 30000 66000
## source_inc e_inc_num_f014 e_inc_num_f014_lo e_inc_num_f014_hi
## 1 Expert opinion NA NA NA
## 2 Expert opinion NA NA NA
## 3 Expert opinion NA NA NA
## 4 Expert opinion NA NA NA
## 5 Expert opinion NA NA NA
## 6 Expert opinion NA NA NA
## e_inc_num_f15plus e_inc_num_f15plus_lo e_inc_num_f15plus_hi e_inc_num_f
## 1 NA NA NA NA
## 2 NA NA NA NA
## 3 NA NA NA NA
## 4 NA NA NA NA
## 5 NA NA NA NA
## 6 NA NA NA NA
## e_inc_num_f_lo e_inc_num_f_hi e_inc_num_m014 e_inc_num_m014_lo
## 1 NA NA NA NA
## 2 NA NA NA NA
## 3 NA NA NA NA
## 4 NA NA NA NA
## 5 NA NA NA NA
## 6 NA NA NA NA
## e_inc_num_m014_hi e_inc_num_m15plus e_inc_num_m15plus_lo e_inc_num_m15plus_hi
## 1 NA NA NA NA
## 2 NA NA NA NA
## 3 NA NA NA NA
## 4 NA NA NA NA
## 5 NA NA NA NA
## 6 NA NA NA NA
## e_inc_num_m e_inc_num_m_lo e_inc_num_m_hi e_inc_num_014 e_inc_num_014_lo
## 1 NA NA NA NA NA
## 2 NA NA NA NA NA
## 3 NA NA NA NA NA
## 4 NA NA NA NA NA
## 5 NA NA NA NA NA
## 6 NA NA NA NA NA
## e_inc_num_014_hi e_inc_num_15plus e_inc_num_15plus_lo e_inc_num_15plus_hi
## 1 NA NA NA NA
## 2 NA NA NA NA
## 3 NA NA NA NA
## 4 NA NA NA NA
## 5 NA NA NA NA
## 6 NA NA NA NA
## e_tbhiv_prct e_tbhiv_prct_lo e_tbhiv_prct_hi e_inc_tbhiv_100k
## 1 0.33 0.27 0.40 0.63
## 2 0.35 0.29 0.42 0.67
## 3 0.37 0.30 0.45 0.70
## 4 0.39 0.32 0.48 0.75
## 5 0.42 0.34 0.50 0.79
## 6 0.44 0.36 0.53 0.83
## e_inc_tbhiv_100k_lo e_inc_tbhiv_100k_hi e_inc_tbhiv_num e_inc_tbhiv_num_lo
## 1 0.38 0.94 120 76
## 2 0.41 0.99 140 83
## 3 0.43 1.00 150 92
## 4 0.45 1.10 170 100
## 5 0.48 1.20 190 110
## 6 0.51 1.20 200 120
## e_inc_tbhiv_num_hi source_tbhiv e_mort_exc_tbhiv_100k
## 1 180 NA 67
## 2 200 NA 61
## 3 220 NA 55
## 4 250 NA 56
## 5 280 NA 50
## 6 300 NA 45
## e_mort_exc_tbhiv_100k_lo e_mort_exc_tbhiv_100k_hi e_mort_exc_tbhiv_num
## 1 39 103 13000
## 2 36 94 13000
## 3 32 85 12000
## 4 33 86 13000
## 5 29 75 12000
## 6 27 68 11000
## e_mort_exc_tbhiv_num_lo e_mort_exc_tbhiv_num_hi e_mort_tbhiv_100k
## 1 7600 20000 0.32
## 2 7300 19000 0.32
## 3 7000 18000 0.30
## 4 7400 19000 0.33
## 5 6900 18000 0.31
## 6 6500 17000 0.30
## e_mort_tbhiv_100k_lo e_mort_tbhiv_100k_hi e_mort_tbhiv_num
## 1 0.21 0.46 64
## 2 0.20 0.46 65
## 3 0.17 0.47 65
## 4 0.19 0.50 74
## 5 0.16 0.50 72
## 6 0.13 0.52 72
## e_mort_tbhiv_num_lo e_mort_tbhiv_num_hi e_mort_100k e_mort_100k_lo
## 1 41 91 67 39
## 2 40 95 62 36
## 3 38 100 56 33
## 4 43 110 57 33
## 5 37 120 50 29
## 6 33 130 46 27
## e_mort_100k_hi e_mort_num e_mort_num_lo e_mort_num_hi source_mort cfr cfr_lo
## 1 103 13000 7700 20000 indirect NA NA
## 2 94 13000 7400 19000 indirect NA NA
## 3 85 12000 7000 18000 indirect NA NA
## 4 86 13000 7500 19000 indirect NA NA
## 5 76 12000 6900 18000 indirect NA NA
## 6 69 11000 6600 17000 indirect NA NA
## cfr_hi c_newinc_100k c_cdr c_cdr_lo c_cdr_hi
## 1 NA 36 19 13 29
## 2 NA 49 26 18 40
## 3 NA 64 34 24 52
## 4 NA 61 32 23 50
## 5 NA 78 41 29 64
## 6 NA 90 47 33 73
JSON
library(jsonlite)
# Enlace que apunta al archivo JSON
url <- "https://raw.githubusercontent.com/curran/data/gh-pages/wallStreetJournal/terrorAttacks/terror-timeline-since-911.json"
# Descargar y parsear el archivo JSON
datos <- fromJSON(url)
# Verificar la estructura de los datos importados
head(datos)
## $myStories
## conflict number
## 1 Sept. 11, 2001, New York 2996
## 2 Oct. 23, 2002, Russia 170
## 3 Oct. 12, 2002, Bali, Indonesia 202
## 4 March 11, 2004, Madrid 191
## 5 Sept. 1, 2004, Beslan, North Ossetia 330
## 6 July 7, 2005, London 52
## 7 Nov. 26, 2008, Mumbai 166
## 8 May 24, 2014, Brussels 4
## 9 Dec. 16, 2014, Pakistan 148
## 10 Jan. 7, 2015, Paris 17
## 11 Oct. 10, 2015, Ankara, Turkey 95
## 12 Oct. 31, 2015, Egypt 224
## 13 March 18, 2015, Tunis, Tunisia 21
## 14 April 2, 2015, Kenya 148
## 15 June 26, 2015, Tunisia and Southeastern France 38
## 16 Nov. 12, 2015, Beirut 43
## 17 July 20, 2015, Turkey 31
## number-text
## 1 2,996 dead
## 2 170 dead, 130 hostages and 40 hostage takers
## 3 202 dead, in the final death toll
## 4 191 dead
## 5 330 dead
## 6 52 dead
## 7 166 dead
## 8 4 dead
## 9 148 dead
## 10 17 dead
## 11 95 dead
## 12 224 dead
## 13 21 dead
## 14 about 150 dead
## 15 38 dead
## 16 43 dead
## 17 31 dead
## Fatalities-confimed-by-another-news-source
## 1 dont delete this
## 2
## 3 But Bali police spokesman Yatim Suyatmo said an additional eight people had died in hospitals overseas as a result of their injuries.
## 4
## 5
## 6
## 7
## 8
## 9
## 10 17
## 11
## 12 224
## 13 22
## 14 148, according to WSJ April 7
## 15 38
## 16 figure appears to be apporximate
## 17 32
## news-source
## 1
## 2 http://www.huffingtonpost.com/2012/10/26/moscow-theatre-siege-2002_n_2022494.html
## 3 http://news.bbc.co.uk/1/hi/world/asia-pacific/2778923.stm
## 4
## 5
## 6
## 7
## 8
## 9
## 10 everywhere
## 11
## 12 Telegraph
## 13 BBC
## 14 http://www.wsj.com/articles/kenya-attacks-spark-anger-and-grief-1428417258
## 15 Independent
## 16
## 17 BBC
## fatalities-according-to-GTD GTD-fatalities-perpetrators
## 1 2996 19
## 2 170 40
## 3 202 NA
## 4 191 NA
## 5 344 NA
## 6 56 4
## 7 183 NA
## 8 4 0
## 9 157 7
## 10 NA NA
## 11 NA NA
## 12 NA NA
## 13 NA NA
## 14 NA NA
## 15 NA NA
## 16 NA NA
## 17 NA NA
## GTD-fatalities-net-of-perps number-reported-at-the-time
## 1 2977 2911
## 2 130 42
## 3 NA 190
## 4 NA 191
## 5 NA 330
## 6 52 52
## 7 NA 166
## 8 4 4
## 9 150 148
## 10 NA 17
## 11 NA 95
## 12 NA 224
## 13 NA 21
## 14 NA 150
## 15 NA 38
## 16 NA 43
## 17 NA 31
## Injured-according-to-GTD ongoing region region-name
## 1 NA namer North America
## 2 NA easteur Eastern Europe
## 3 300 asia Asia
## 4 1800 westeur Western Europe
## 5 727 yes easteur Eastern Europe
## 6 784 westeur Western Europe
## 7 252 no asia Asia
## 8 NA eurwest Western Europe
## 9 131 yes asia Asia
## 10 NA meast Western Europe
## 11 NA yes easteur Eastern Europe
## 12 NA no meast Middle East
## 13 NA meast Middle East
## 14 NA africa Africa
## 15 NA meast Middle East
## 16 NA meast Middle East
## 17 NA no easteur Eastern Europe
## link
## 1 #
## 2 http://www.wsj.com/articles/SB1035398765975326831
## 3 http://www.wsj.com/articles/SB1034626542477954196
## 4 http://www.wsj.com/articles/SB107899319607552435
## 5 http://www.wsj.com/articles/SB121122113835904159
## 6 #
## 7 http://www.wsj.com/articles/SB121122113835904159
## 8 http://www.wsj.com/articles/SB10001424052702303480304579582053876109192
## 9 http://www.wsj.com/articles/taliban-militants-attack-pakistan-school-1418716418
## 10 http://www.wsj.com/articles/islamist-terror-in-paris-1420675706
## 11 http://www.wsj.com/articles/turkish-capital-ankara-hit-by-explosions-killing-at-least-30-1444470335
## 12 http://www.wsj.com/articles/russian-passenger-jet-crashes-in-egypts-sinai-peninsula-1446281838
## 13 http://www.wsj.com/articles/attack-in-tunisias-museum-kills-20-1426735719
## 14 http://www.wsj.com/articles/gunmen-attack-kenyan-university-firing-randomly-in-student-hostels-1427960178
## 15 http://www.wsj.com/articles/twenty-seven-killed-in-attacks-on-tunisian-hotels-1435321844
## 16 http://www.wsj.com/articles/two-bombing-attacks-hit-beirut-suburb-1447348870
## 17 http://www.wsj.com/articles/turkish-town-of-suruc-hit-by-deadly-blast-1437388272
## year
## 1 20010911
## 2 20021023
## 3 20021012
## 4 20040311
## 5 20040901
## 6 20050707
## 7 20081126
## 8 20140524
## 9 20141216
## 10 20150107
## 11 20151010
## 12 20151031
## 13 20150315
## 14 20150402
## 15 20150626
## 16 20151112
## 17 20150720
## date-in-GTD-for-2014-and-before-news-acccounts-for-2015-if-different
## 1 9/11/2001
## 2 10/23/2002
## 3 10/12/2002
## 4 3/11/2004
## 5 9/1/2004
## 6 7/7/2005
## 7 11/26/2008
## 8 5/24/2014
## 9 12/16/2014
## 10 1/7/2015
## 11 10/10/2015
## 12 10/31/2015
## 13 3/18/2015
## 14 4/2/2015
## 15 6/26/2015
## 16 11/12/2015
## 17 7/20/2015
## image
## 1 http://s.wsj.net/public/resources/images/BN-LG479_tertim_G_20151114104950.jpg
## 2 http://s.wsj.net/public/resources/images/BN-LG480_tertim_G_20151114104950.jpg
## 3 http://s.wsj.net/public/resources/images/BN-LG478_tertim_G_20151114104950.jpg
## 4 http://s.wsj.net/public/resources/images/BN-LG482_tertim_G_20151114104950.jpg
## 5 http://s.wsj.net/public/resources/images/BN-LG481_tertim_G_20151114104950.jpg
## 6 http://s.wsj.net/public/resources/images/BN-LG483_tertim_G_20151114104950.jpg
## 7 http://s.wsj.net/public/resources/images/BN-LG484_tertim_G_20151114105003.jpg
## 8 http://s.wsj.net/public/resources/images/BN-LG502_tertim_G_20151114112439.jpg
## 9 http://s.wsj.net/public/resources/images/BN-LG489_tertim_G_20151114105007.jpg
## 10 http://s.wsj.net/public/resources/images/BN-LG485_tertim_G_20151114105004.jpg
## 11 http://s.wsj.net/public/resources/images/BN-LG488_tertim_G_20151114105006.jpg
## 12 http://s.wsj.net/public/resources/images/BN-LG490_tertim_G_20151114105019.jpg
## 13 http://s.wsj.net/public/resources/images/BN-LG487_tertim_G_20151114105006.jpg
## 14 http://s.wsj.net/public/resources/images/BN-LG486_tertim_G_20151114105005.jpg
## 15 http://s.wsj.net/public/resources/images/BN-LG491_tertim_G_20151114105019.jpg
## 16 http://s.wsj.net/public/resources/images/BN-LG500_tertim_G_20151114111959.jpg
## 17 http://s.wsj.net/public/resources/images/BN-LG492_tertim_G_20151114105019.jpg
## caption
## 1 The twin towers of the World Trade Center burn after hijacked planes crashed into them on September 11, 2001 in New York City.(AP Photo/Louis Lanzano)// ASSOCIATED PRESS
## 2 A special forces officer helps a female out of the theater where hundreds of hostages were being held by Chechen rebels, in Moscow, early Saturday Oct. 26, 2002. Special forces troops took control of a Moscow theater before sunrise Saturday where hundreds of hostages were being held by Chechen rebels, killing their leader and freeing all their captives. (AP Photo/Dmitry Lovetsky)// A WOMAN IS ESCORTED OUT OF THE THEATER IN MOSCOW. ASSOCIATED PRESS
## 3 The wreckage of the Sari night club and surrounding buildings are seen in this aerial view Tuesday, Oct. 15, 2002 in Kuta, Bali. Two powerful explosions near the popular night spot killed over 180 people and left hundreds injured in the worst ever terrorist attack in Indonesia. (AP Photo/Achmad Ibrahim)//WRECKAGE OF THE NIGHT CLUB SEEN IN BALI. ASSOCIATED PRESS
## 4 Bodies of victims are evacuated after a train exploded near the Atocha train station in Madrid 11 March 2004. At least 131 people were killed and some 400 injured early 11 March 2004 in near-simultaneous explosions on three trains in Madrid at the height of morning commuter traffic, the Spanish interior ministry said. In what appeared to be a deliberate attack staged only 72 hours ahead of Spanish general elections, the blasts went off on a long-distance high-speed carrier and two suburban trains packed with commuters. (Photo credit should read CHRISTOPHE SIMON/AFP/Getty Images) ///
## 5 Special forces soldiers evacuate a little girl and a woman, apparently after they escaped from a school, which is seized by attackers in the town of Beslan, about 15 kilometers (10 miles) north of Vladikavkaz, the capital of North Ossetia, a republic that borders warring Chechnya, in this image taken from television, Wednesday, Sept.1, 2004. About a score of attackers bearing guns and wrapped in suicide-bomb belts seized a school in the Russian region of North Ossetia Wednesday morning and were in a gun battle with police. (AP Photo/RTR, Russian Television, via APTN) /// A WOMAN AND A GIRL ESCAPE FROM THE SCHOOL IN BESLAN. APTN/ASSOCIATED PRESS
## 6 ** FILE ** A forensic officer walks next to the wreckage of a double decker bus with its top blown off and damaged cars scattered on the road at Tavistock Square in central London in this Thursday, July 7, 2005, file photo. A string of rush-hour explosions blamed on Islamic terrorists tore into at least three London subway trains and a double-decker bus on Thursday. Friday July 7, 2006 marks the first anniversary of the terrorist attacks in London that killed 52 commuters. (AP Photo/Sang Tan)
## 7 Indian army soldiers take position during a gun battle at the Taj Mahal hotel (seen in the background) in Mumbai November 29, 2008. Operations by Indian commandos to dislodge Islamist militants at Mumbai's Taj Mahal hotel ended on Saturday, Indian television channels quoted officials as saying. The hotel came under heavy gunfire and flames leaped out of the building shortly before the announcement. REUTERS/Desmond Boylan (INDIA) - RTR222U1
## 8 Forensic experts examine the site of a shooting at the Jewish museum in Brussels, Saturday, May 24, 2014. Belgian officials say that at least three people have been killed in gunfire at the Jewish Museum in Brussels. Belgian Foreign Minister Didier Reynders, in a post on Twitter, said he was
## 9 Pakistani volunteers carry a student injured in the shootout at a school under attack by Taliban gunmen, at a local hospital in Peshawar, Pakistan,Tuesday, Dec. 16, 2014. Taliban gunmen stormed a military school in the northwestern Pakistani city, killing and wounding dozens, officials said, in the latest militant violence to hit the already troubled region. (AP Photo/Mohammad Sajjad)
## 10 Gunmen gesture as they return to their car after the attack outside the offices of French satirical weekly newspaper Charlie Hebdo (seen at rear) in this still image taken from amateur video shot in Paris January 7, 2015. Twelve people were slain, including two police officers, during last week's attack by Islamist militants Cherif and Said Kouachi. REUTERS/Reuters TV (FRANCE - Tags: CRIME LAW MEDIA TPX IMAGES OF THE DAY) - RTR4LARW
## 11 An injured woman is comforted following an explosion at the main train station in Turkey's capital Ankara, on October 10, 2015. At least 30 people were killed and 126 were injured in the explosion which happened ahead of an anti-government peace rally organised by leftist groups later in the day, including the pro-Kurdish Peoples' Democratic Party (HDP). AFP PHOTO / ADEM ALTAN (Photo credit should read ADEM ALTAN/AFP/Getty Images)
## 12 TOPSHOTS A handout picture taken on November 1, 2015 and released on November 3, 2015 by Russia's Emergency Ministry shows the wreckage of a A321 Russian airliner in Wadi al-Zolomat, a mountainous area of Egypt's Sinai Peninsula. Russian airline Kogalymavia's flight 9268 crashed en route from Sharm el-Sheikh to Saint Petersburg on October 31, killing all 224 people on board, the vast majority of them Russian tourists. wreckage of a A321 AFP PHOTO / RUSSIA'S EMERGENCY MINISTRY / MAXIM GRIGORYEV *RESTRICTED TO EDITORIAL USE - MANDATORY CREDIT AFP PHOTO / RUSSIA'S EMERGENCY MINISTRY / MAXIM GRIGORYEV - NO MARKETING NO ADVERTISING CAMPAIGNS - DISTRIBUTED AS A SERVICE TO CLIENTS *MAXIM GRIGORYEV/AFP/Getty Images
## 13 TUNIS, TUNISIA - MARCH 18 : Museum attack hostages are seen after Tunisian Security forces start an operation as gunmen reportedly took hostages at the Bardo Museum in Tunis, Tunisia on March 18, 2015. Gunmen opened fire at the Bardo Museum in Tunisia's capital, killing 21 people including 17 tourists, the Tunisian Prime Minister said. (Photo by Ezer Mnasri/Anadolu Agency/Getty Images)
## 14 Students of the Garissa University College take shelter in a vehicle after fleeing from an attack by gunmen in Garissa, Kenya, Thursday, April 2, 2015. Gunmen attacked the university early Thursday, shooting indiscriminately in campus hostels. Police and military surrounded the buildings and were trying to secure the area in eastern Kenya, police officer Musa Yego said. (AP Photo)
## 15 Tunisian men help an injured woman in the resort town of Sousse, a popular tourist destination 140 kilometres (90 miles) south of the Tunisian capital, on June 26, 2015, following a shooting attack. At least 27 people, including foreigners, were killed in a mass shooting at a Tunisian beach resort packed with holidaymakers, in the North African country's worst attack in recent history. AFP PHOTO / FETHI BELAID (Photo credit should read FETHI BELAID/AFP/Getty Images)
## 16 Members of the Lebanese police forces and Hezbollah inspect the site of a twin suicide attack in the Bourj al-Barajneh suburb of Beirut, Lebanon, Nov. 15, 2015. According to local sources at least 43 civilians were killed and over 235 wounded when two suicide attackers blew themselves up 12 November near a busy market outside the al-Imam al-Hussein mosque on al-Husseiniya street in the suburb with a large Hezbollah presence. The group calling themselves the Islamic State (IS) has claimed responsibility for the attack, after which a day of mourning was decalred in Lebanon for 13 November. EPA/WAEL HAMZEH
## 17 Turkish policemen stand next to bodies of victims on July 20, 2015 after an explosion in the town of Suruc, not far from the Syrian border. At least 30 people were killed and hundreds injured in a suicide bombing aiming the garden of a cultural centre where young left-wing activists and pro-Kurds lived. Turkish officials largely blamed the attack on Islamic State militants. AFP PHOTO / ILYAS AKENGIN (Photo credit should read ILYAS AKENGIN/AFP/Getty Images)
## text
## 1 The September 11 attacks kill nearly 3,000 people. Terrorists crash passenger jets into the Twin Towers of the World Trade Center in Manhattan and the Pentagon in Virginia, and a fourth airplane crashes in a western Pennsylvania field.
## 2 Forty Chechen fighters seize Moscow's Dubrovka Theater and hold nearly 1,000 people hostage, killing two. Russian special forces storm the building after pumping a chemical agent into the ventilation system, killing all 40 terrorists and some 130 hostages because of an adverse reaction to the gas.
## 3 Indonesian officials blame al Qaeda for a car bomb that kills nearly 190 people on the Indonesian holiday island of Bali.
## 4 Coordinated bomb attacks hit four Spanish commuter trains in Madrid, killing 191 people. Spanish investigators blame an al Qaeda-linked terror cell.
## 5 A massacre leaves more than 330 dead, around half of them children, after Islamist terrorists take 1,200 people hostage in Beslan, North Ossetia, an autonomous Russian republic. The siege lasts for three days.
## 6 Four coordinated attacks by suicide bombers rip through London subway trains and a bus, killing 52 rush-hour commuters. The killers are later identified as British al Qaeda sympathizers Shehzad Tanweer, Hasib Hussain, Mohammed Sidique Khan and Jermaine Lindsay.
## 7 A 60-hour siege by 10 militants from Pakistan on India’s biggest city and financial capital kills 166 people. India claims the terrorists who perpetrated the attacks on luxury hotels, a Jewish center and other sites were operatives of the Pakistan-based militant group Lashkar-e-Taiba.
## 8 A gunman murders four people at the Jewish Museum of Belgium in Brussels. Mehdi Nemmouche, a French national with ties to Islamic State, is arrested and charged with the killings.
## 9 Taliban gunmen storm a military-run school in northwestern Pakistan and kill at least 148 people, methodically shooting schoolchildren in the head and setting fire to some victims in a horrifying nine-hour rampage.
## 10 Islamist extremists kill a total of 17 people at Paris-based satirical magazine Charlie Hebdo and a kosher grocery in the city.
## 11 Twin suicide bombings kill about 95 people in the Turkish capital of Ankara. The Turkish government first attributes the attacks to Islamic State, but later says an inquiry points to the Kurdish Workers' Party, or PKK.
## 12 A Russian-operated jet crashes in Egypt, killing all 224 people on board, in what appears to have been a terrorist act. Islamic State claims responsibility.
## 13 Several men carry out a shooting attack at the Bardo National Museum in Tunisia's capital, killing 21. Islamic State claims responsibility.
## 14 Heavily armed gunmen storm a university campus in Kenya, setting off a rampage that leaves about 150 dead in an attack associated with Somalia-based Islamist group al-Shabaab.
## 15 A lone gunman storms a beach resort in Tunisia, killing 37 people. Islamic State claims responsibility. On the same day, a man decapitates his boss at a U.S.-owned industrial gas plant in southeastern France.
## 16 A double suicide bombing in a Beirut suburb kills around 43 people, in an attack that bore the hallmarks of Sunni militants linked to al Qaeda and other extremist groups.
## 17 Turkey’s government blames Islamic State for a suicide bombing in a Kurdish border town that kills at least 31 people, one of the worst cases of spillover violence from the 4 1/2-year conflict in neighboring Syria.
## caption-edited
## 1 PHOTO: ASSOCIATED PRESS
## 2 A woman is escorted out of the theater in Moscow. PHOTO: ASSOCIATED PRESS
## 3 Site of the attack in Bali. PHOTO: ASSOCIATED PRESS
## 4 Wreckage of a train hit by a bomb in Atocha, Madrid. PHOTO: AGENCE FRANCE-PRESSE/GETTY IMAGES
## 5 A woman and a girl escape in Beslan. PHOTO: APTN/ASSOCIATED PRESS
## 6 Wreckage of a bus in London. PHOTO: ASSOCIATED PRESS
## 7 Taj Mahal hotel during the attack. PHOTO: REUTERS
## 8 Investigators seek clues outside the museum. PHOTO: ASSOCIATED PRESS
## 9 Volunteers carry an injured student. PHOTO: ASSOCIATED PRESS
## 10 Gunmen gesture after the attack. PHOTO: REUTERS
## 11 People outside Ankara train station. PHOTO: AGENCE FRANCE-PRESSE/GETTY IMAGES
## 12 PHOTO: RUSSIA'S EMERGENCY MINISTRY/AGENCE FRANCE-PRESSE
## 13 Hostages are released. PHOTO: GETTY IMAGES
## 14 Students take shelter. PHOTO: ASSOCIATED PRESS
## 15 A victim gets help in Sousse, Tunis. PHOTO: AGENCE FRANCE-PRESSE/GETTY IMAGES
## 16 Police inspect the site in Beirut. PHOTO: EUROPEAN PRESSPHOTO AGENCY
## 17 Police stand next to bodies in Suruc, Syria. PHOTO: AGENCE FRANCE-PRESSE/GETTY IMAGES
CSS
library(readr)
# URL del archivo CSV en GitHub
url_github <- "https://raw.githubusercontent.com/securitytxt/securitytxt.org/master/css/stylesheet.css"
# Leer el archivo CSV desde GitHub
datos <- read_csv(url_github)
## Rows: 77 Columns: 1
## ── Column specification ────────────────────────────────────────────────────────
## Delimiter: ","
## chr (1): /* Layout */
##
## ℹ 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.
# Ver las primeras filas del data frame para verificar que se cargaron correctamente
head(datos)
## # A tibble: 6 × 1
## `/* Layout */`
## <chr>
## 1 html {
## 2 overflow: auto;
## 3 }
## 4 body {
## 5 display: flex;
## 6 min-height: 100vh;
Identificar y manejar datos faltantes es crucial en el análisis de datos. Puedes manejar datos faltantes en R al cargar datos desde una URL utilizando diversas funciones y paquetes.
Por ejemplo, si estás leyendo un archivo CSV desde una URL y quieres manejar los valores faltantes, podemos usar la función ¨na.omit()¨ para eliminar las filas que contienen datos faltantes.
Tenemos nuestro archivo CSV en una URL y queremos manejar los datos faltantes al cargarlos en R:
library(readr)
# URL del archivo CSV
url <- "https://raw.githubusercontent.com/d99kris/rapidcsv/master/examples/colrowhdr.csv"
# Cargar el archivo CSV desde la URL
datos <- read_csv(url)
## Rows: 5 Columns: 7
## ── Column specification ────────────────────────────────────────────────────────
## Delimiter: ","
## dbl (6): Open, High, Low, Close, Volume, Adj Close
## date (1): Date
##
## ℹ 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.
# Verificar la cantidad de datos faltantes en cada columna
colSums(is.na(datos))
## Date Open High Low Close Volume Adj Close
## 0 0 0 0 0 0 0
# Eliminar filas con datos faltantes
datos_sin_faltantes <- na.omit(datos)
El código anterior carga el archivo CSV desde la URL, luego usa ¨colSums(is.na(datos))¨ para mostrar la cantidad de datos faltantes en cada columna y finalmente utiliza ¨na.omit()¨ para eliminar las filas que contienen datos faltantes, almacenando los datos limpios en ¨datos_sin_faltantes¨.
Identificacion: Los datos atípicos (outliers en inglés) son puntos o valores que difieren significativamente del resto de los datos en un conjunto. En general, los outliers son observaciones que se apartan de la distribución típica de los datos y pueden ser el resultado de errores en la medición, eventos raros, o simplemente representar fenómenos inusuales pero legítimos.
library(readr)
# URL del archivo CSV
url <- "https://raw.githubusercontent.com/d99kris/rapidcsv/master/examples/colhdr.csv"
# Cargar el archivo CSV desde la URL
datos <- read_csv(url)
## Rows: 5 Columns: 6
## ── Column specification ────────────────────────────────────────────────────────
## Delimiter: ","
## dbl (6): Open, High, Low, Close, Volume, Adj Close
##
## ℹ 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.
# Calcular el rango intercuartílico (IQR) para cada columna
iqr_values <- apply(datos, 2, IQR)
# Calcular los límites para identificar outliers
outlier_limit <- 1.5 * iqr_values
# Identificar outliers en cada columna
outliers <- apply(datos, 2, function(x) x < quantile(x, 0.25) - outlier_limit | x > quantile(x, 0.75) + outlier_limit)
## Warning in x < quantile(x, 0.25) - outlier_limit: longitud de objeto mayor no
## es múltiplo de la longitud de uno menor
## Warning in x > quantile(x, 0.75) + outlier_limit: longitud de objeto mayor no
## es múltiplo de la longitud de uno menor
## Warning in x < quantile(x, 0.25) - outlier_limit: longitud de objeto mayor no
## es múltiplo de la longitud de uno menor
## Warning in x > quantile(x, 0.75) + outlier_limit: longitud de objeto mayor no
## es múltiplo de la longitud de uno menor
## Warning in x < quantile(x, 0.25) - outlier_limit: longitud de objeto mayor no
## es múltiplo de la longitud de uno menor
## Warning in x > quantile(x, 0.75) + outlier_limit: longitud de objeto mayor no
## es múltiplo de la longitud de uno menor
## Warning in x < quantile(x, 0.25) - outlier_limit: longitud de objeto mayor no
## es múltiplo de la longitud de uno menor
## Warning in x > quantile(x, 0.75) + outlier_limit: longitud de objeto mayor no
## es múltiplo de la longitud de uno menor
## Warning in x < quantile(x, 0.25) - outlier_limit: longitud de objeto mayor no
## es múltiplo de la longitud de uno menor
## Warning in x > quantile(x, 0.75) + outlier_limit: longitud de objeto mayor no
## es múltiplo de la longitud de uno menor
## Warning in x < quantile(x, 0.25) - outlier_limit: longitud de objeto mayor no
## es múltiplo de la longitud de uno menor
## Warning in x > quantile(x, 0.75) + outlier_limit: longitud de objeto mayor no
## es múltiplo de la longitud de uno menor
# Mostrar los índices de filas que contienen outliers en al menos una columna
indices_outliers <- which(rowSums(outliers) > 0)
print(indices_outliers)
## Open Low Adj Close
## 1 3 6
Este código calcula los límites para identificar outliers en cada columna utilizando el rango intercuartílico (IQR) y la regla de 1.5 veces el IQR. Luego, identifica los índices de las filas que contienen outliers en al menos una columna del conjunto de datos.
Manejo de datos outlier:
El manejo de datos atípicos (outliers) depende en gran medida del contexto del análisis y la naturaleza de los datos. Aquí te presento algunas estrategias comunes para manejar outliers una vez que los has identificado en tus datos:
Eliminación: Puedes eliminar los outliers si tienes razones para creer que son errores de medición o datos incorrectos. Sin embargo, la eliminación de outliers debe hacerse con cuidado, ya que puede afectar la integridad y representatividad de tus datos. Puedes eliminarlos por completo o considerar imputar valores en su lugar.
Transformación: En algunos casos, aplicar transformaciones a los datos, como logaritmos o raíces cuadradas, puede reducir el impacto de los outliers en el análisis estadístico. Estas transformaciones pueden hacer que la distribución de los datos sea más simétrica y más adecuada para ciertos modelos.
Segmentación: Puedes dividir tus datos en segmentos o grupos más pequeños y analizar los outliers en cada grupo por separado. Esto puede proporcionar información más detallada sobre por qué ciertos puntos son outliers en un contexto específico.
Análisis específico: Si los outliers son parte de un fenómeno genuino o representan datos importantes, podrías necesitar un análisis más profundo para entender por qué son distintos y si tienen un impacto significativo en tus conclusiones.
Usar métodos robustos: Algunos métodos estadísticos son menos sensibles a los outliers que otros. Por ejemplo, usar la mediana en lugar del promedio puede ser menos afectado por valores extremos en los datos. Ejemplo:
library(readr)
# URL del archivo CSV
url <- "https://raw.githubusercontent.com/d99kris/rapidcsv/master/examples/colhdr.csv"
# Cargar el archivo CSV desde la URL
datos <- read_csv(url)
## Rows: 5 Columns: 6
## ── Column specification ────────────────────────────────────────────────────────
## Delimiter: ","
## dbl (6): Open, High, Low, Close, Volume, Adj Close
##
## ℹ 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.
# Calcular el IQR para una columna específica (por ejemplo, 'columna_ejemplo')
columna_ejemplo <- 'High' # Reemplaza con el nombre de tu columna de interés
Q1 <- quantile(datos[[columna_ejemplo]], 0.25)
Q3 <- quantile(datos[[columna_ejemplo]], 0.75)
IQR_valor <- Q3 - Q1
# Calcular los límites para identificar outliers
limite_inferior <- Q1 - 1.5 * IQR_valor
limite_superior <- Q3 + 1.5 * IQR_valor
# Identificar y manejar outliers en la columna
outliers <- datos[[columna_ejemplo]] < limite_inferior | datos[[columna_ejemplo]] > limite_superior
# Mostrar los índices de filas que contienen outliers
indices_outliers <- which(outliers)
print(indices_outliers)
## [1] 3
# Manejar outliers (por ejemplo, asignarles NA)
datos[outliers, columna_ejemplo] <- NA
En este ejemplo, los pasos son:
Cargamos el conjunto de datos desde la URL.
Calculamos el rango intercuartílico (IQR) para una columna específica.
Definimos los límites para identificar outliers.
Identificamos los outliers en la columna especificada.
Mostramos los índices de filas que contienen outliers.
Manejamos los outliers asignándoles un valor NA en la columna.
La limpieza de datos es un paso crucial en el proceso de análisis de datos. Incluye varias tareas, como identificar y manejar valores faltantes, eliminar duplicados, corregir errores, estandarizar formatos, entre otros.
En el siguiente ejemplo:
Cargamos el conjunto de datos desde la URL.
Utilizamos ¨na.omit()¨ para eliminar las filas que contienen valores faltantes.
Empleamos ¨unique()¨ para eliminar filas duplicadas.
Opcionalmente, guardamos los datos limpios en un nuevo archivo CSV utilizando ¨write_csv()¨.
library(readr)
# URL del archivo CSV
url <- "https://raw.githubusercontent.com/d99kris/rapidcsv/master/examples/colhdr.csv"
# Cargar el archivo CSV desde la URL
datos <- read_csv(url)
## Rows: 5 Columns: 6
## ── Column specification ────────────────────────────────────────────────────────
## Delimiter: ","
## dbl (6): Open, High, Low, Close, Volume, Adj Close
##
## ℹ 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.
# Identificar y manejar valores faltantes
datos_sin_na <- na.omit(datos) # Eliminar filas con valores faltantes
# Eliminar filas duplicadas
datos_sin_duplicados <- unique(datos_sin_na)
# Verificar los cambios
head(datos_sin_duplicados) # Mostrar las primeras filas de los datos limpios
## # A tibble: 5 × 6
## Open High Low Close Volume `Adj Close`
## <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
## 1 64.5 64.8 64.1 64.6 21705200 64.6
## 2 64.4 64.7 64.2 64.6 20235200 64.6
## 3 64.3 64.4 64.1 64.4 19259700 64.4
## 4 64.6 64.9 64.4 64.5 19384900 64.5
## 5 64.5 64.7 64.3 64.6 21234600 64.6
En este ejemplo:
Cargamos el conjunto de datos desde la URL.
Utilizamos ¨na.omit()¨ para eliminar las filas que contienen valores faltantes.
Empleamos ¨unique()¨ para eliminar filas duplicadas.
Opcionalmente, guardamos los datos limpios en un nuevo archivo CSV utilizando ¨write_csv()¨.
La visualización de datos univariados implica explorar y representar gráficamente una única variable.
Histograma
El histograma muestra la distribución de una variable numérica dividiéndola en intervalos (bins) y mostrando la frecuencia en cada intervalo.
library(readr)
library(ggplot2)
## Warning: package 'ggplot2' was built under R version 4.3.2
# URL del archivo CSV
url <- "https://raw.githubusercontent.com/d99kris/rapidcsv/master/examples/colhdr.csv"
# Cargar el archivo CSV desde la URL
datos <- read_csv(url)
## Rows: 5 Columns: 6
## ── Column specification ────────────────────────────────────────────────────────
## Delimiter: ","
## dbl (6): Open, High, Low, Close, Volume, Adj Close
##
## ℹ 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.
# Visualización: Histograma de una columna específica (por ejemplo, 'columna_ejemplo')
columna_ejemplo <- 'Volume' # Reemplaza con el nombre de tu columna de interés
ggplot(datos, aes(x = datos[[columna_ejemplo]])) +
geom_histogram(bins = 20, fill = "lightyellow", color = "black") +
labs(x = "Valores", y = "Frecuencia", title = "Histograma de 'nombre_de_la_columna'")
Gráfico de barras (para variables categóricas)
El gráfico de barras muestra la frecuencia de las categorías en una variable categórica.
library(readr)
library(ggplot2)
# URL del archivo CSV
url <- "https://raw.githubusercontent.com/Anthony6197/data/81d8f346256a2b3b4f52bf4cb9931e9220e0063d/covid-geography/mmsa-icu-beds.csv"
# Cargar el archivo CSV desde la URL
datos <- read_csv(url)
## Rows: 136 Columns: 7
## ── Column specification ────────────────────────────────────────────────────────
## Delimiter: ","
## chr (2): MMSA, total_percent_at_risk
## dbl (5): high_risk_per_ICU_bed, high_risk_per_hospital, icu_beds, hospitals,...
##
## ℹ 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.
# Visualización: Gráfico de barras de una columna categórica (por ejemplo, 'columna_categorica')
columna_categorica <- 'hospitals' # Reemplaza con el nombre de tu columna de interés
ggplot(datos, aes(x = factor(datos[[columna_categorica]]))) +
geom_bar(fill = "pink", color = "black") +
labs(x = "Categorías", y = "Frecuencia", title = "Gráfico de barras de 'total_percent_at_risk'")
La visualización de datos bivariados implica explorar y representar gráficamente la relación entre dos variables.
Diagrama de dispersión:
El diagrama de dispersión muestra la relación entre dos variables numéricas.
library(readr)
library(ggplot2)
# URL del archivo CSV
url <- "https://raw.githubusercontent.com/Anthony6197/data/81d8f346256a2b3b4f52bf4cb9931e9220e0063d/covid-geography/mmsa-icu-beds.csv"
# Cargar el archivo CSV desde la URL
datos <- read_csv(url)
## Rows: 136 Columns: 7
## ── Column specification ────────────────────────────────────────────────────────
## Delimiter: ","
## chr (2): MMSA, total_percent_at_risk
## dbl (5): high_risk_per_ICU_bed, high_risk_per_hospital, icu_beds, hospitals,...
##
## ℹ 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.
# Visualización: Diagrama de dispersión entre dos columnas (por ejemplo, 'columna_x' y 'columna_y')
columna_x <- 'total_percent_at_risk' # Reemplaza con el nombre de tu primera columna de interés
columna_y <- 'high_risk_per_ICU_bed' # Reemplaza con el nombre de tu segunda columna de interés
ggplot(datos, aes(x = datos[[columna_x]], y = datos[[columna_y]])) +
geom_point(color = "blue") +
labs(x = "Variable X", y = "Variable Y", title = "Diagrama de dispersión entre 'columna_x' y 'columna_y'")
## Warning: Removed 1 rows containing missing values (`geom_point()`).
Gráfico de barras agrupadas (para variables categóricas):
Muestra la relación entre dos variables categóricas usando barras agrupadas.
library(readr)
library(ggplot2)
# URL del archivo CSV
url <- "https://raw.githubusercontent.com/Anthony6197/data/81d8f346256a2b3b4f52bf4cb9931e9220e0063d/covid-geography/mmsa-icu-beds.csv"
# Visualización: Gráfico de barras agrupadas entre dos columnas categóricas (por ejemplo, 'columna_x' y 'columna_y')
columna_x <- 'total_at_risk' # Reemplaza con el nombre de tu primera columna de interés
columna_y <- 'high_risk_per_ICU_bed' # Reemplaza con el nombre de tu segunda columna de interés
ggplot(datos, aes(x = factor(datos[[columna_x]]), fill = factor(datos[[columna_y]]))) +
geom_bar(position = "dodge", color = "black") +
labs(x = "Variable X", y = "Frecuencia", title = "Gráfico de barras agrupadas entre 'columna_x' y 'columna_y'")
La visualización de datos bivariados multivariados explora y representa gráficamente las relaciones entre múltiples variables simultáneamente.
library(readr)
# URL del archivo CSV
url <- "https://raw.githubusercontent.com/Anthony6197/data/81d8f346256a2b3b4f52bf4cb9931e9220e0063d/covid-geography/mmsa-icu-beds.csv"
# Cargar el archivo CSV desde la URL
datos <- read_csv(url)
## Rows: 136 Columns: 7
## ── Column specification ────────────────────────────────────────────────────────
## Delimiter: ","
## chr (2): MMSA, total_percent_at_risk
## dbl (5): high_risk_per_ICU_bed, high_risk_per_hospital, icu_beds, hospitals,...
##
## ℹ 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.
# Visualización: Gráfico de pares para explorar relaciones entre variables
pairs(datos[, c("total_at_risk", "hospitals", "high_risk_per_ICU_bed")],
main = "Gráfico de pares para 'total_at_risk', 'hospitals' y 'high_risk_per_ICU_bed'")
Para visualizar imágenes desde un enlace en R, puedes utilizar la función readJPEG() del paquete jpeg, readPNG() del paquete png, o readTIFF() del paquete tiff para leer y mostrar imágenes desde una URL.
library(png)
# URL de la imagen PNG
url_png <- "https://www.pinpng.com/pngs/m/274-2742184_pato-pocoyo-png-imagenes-de-pato-de-pocoyo.png"
# Nombre del archivo local donde se guardará la imagen
nombre_archivo <- "pato_pocoyo.png"
# Descargar la imagen desde la URL a tu directorio local
download.file(url_png, destfile = nombre_archivo, mode = "wb")
# Leer la imagen desde tu directorio local
imagen_png <- readPNG(nombre_archivo)
# Mostrar la imagen
plot(0:1, 0:1, type = "n", xlab = "", ylab = "", xlim = c(0, 1), ylim = c(0, 1))
rasterImage(imagen_png, 0, 0, 1, 1)
Mostrar valores RGB
Para obtener los valores RGB de una imagen en R, primero necesitas leer la imagen y luego acceder a los valores de los píxeles. Puedes usar el paquete jpeg o png para leer la imagen y luego acceder a los valores de los píxeles para obtener los componentes RGB.
library(png)
# URL de la imagen PNG
url_png <- "https://www.pinpng.com/pngs/m/274-2742184_pato-pocoyo-png-imagenes-de-pato-de-pocoyo.png"
# Nombre del archivo local donde se guardará la imagen
nombre_archivo <- "pato_pocoyo.png"
# Descargar la imagen desde la URL a tu directorio local
download.file(url_png, destfile = nombre_archivo, mode = "wb")
# Leer la imagen desde tu directorio local
imagen <- readPNG(nombre_archivo)
# Obtener las dimensiones de la imagen
dim_imagen <- dim(imagen)
# Crear una matriz para almacenar los valores RGB de los píxeles
valores_rgb <- matrix(NA, nrow = dim_imagen[1], ncol = dim_imagen[2])
# Obtener los valores RGB de cada píxel
for (i in 1:dim_imagen[1]) {
for (j in 1:dim_imagen[2]) {
valores_rgb[i, j] <- paste0("R:", imagen[i, j, 1], " G:", imagen[i, j, 2], " B:", imagen[i, j, 3])
}
}
# Mostrar algunos valores RGB (por ejemplo, primeros 10 píxeles)
print(valores_rgb[1:10, 1])
## [1] "R:1 G:1 B:1" "R:1 G:1 B:1" "R:1 G:1 B:1" "R:1 G:1 B:1" "R:1 G:1 B:1"
## [6] "R:1 G:1 B:1" "R:1 G:1 B:1" "R:1 G:1 B:1" "R:1 G:1 B:1" "R:1 G:1 B:1"
La manipulación de datos no estructurados se refiere a la transformación, limpieza y procesamiento de datos que no están organizados en una estructura tabular o en una base de datos convencional. Esto puede incluir datos de texto, imágenes, audio, video, redes sociales o cualquier otro tipo de información que no siga un formato claro y organizado.
Aquí hay algunas estrategias comunes para manipular datos no estructurados:
Datos de Texto:
Tokenización: Dividir texto en unidades más pequeñas, como palabras o frases.
Limpieza de texto: Eliminar caracteres especiales, puntuación, o realizar corrección ortográfica.
Procesamiento de lenguaje natural (NLP): Extracción de entidades, análisis de sentimientos, clasificación de texto, entre otros.
Para realizar alguna manipulación específica con el contenido de nuestro archivo llamado CMakeLists.txt desde la URL proporcionada en R, podemos usar el siguiente código como punto de partida para realizar algunas operaciones:
Mostrar primeras lineas
library(httr)
## Warning: package 'httr' was built under R version 4.3.2
# URL del archivo de texto
url <- "https://raw.githubusercontent.com/d99kris/rapidcsv/master/CMakeLists.txt"
# Realizar la solicitud GET para obtener el contenido del archivo
respuesta <- GET(url)
# Verificar el estado de la respuesta
if (http_type(respuesta) == "text/plain") {
# Leer el contenido del archivo
contenido <- content(respuesta, as = "text")
# Realizar alguna manipulación específica aquí (por ejemplo, mostrar las primeras 10 líneas)
lineas <- strsplit(contenido, "\n")[[1]]
primeras_10_lineas <- head(lineas, 10)
cat(primeras_10_lineas, sep = "\n")
} else {
cat("No se pudo obtener el archivo de texto.")
}
## # Project
## cmake_minimum_required(VERSION 3.1 FATAL_ERROR)
## project(rapidcsv VERSION 1.0 LANGUAGES CXX)
## set (CMAKE_CXX_STANDARD 11)
## if(MSVC)
## if(CMAKE_CXX_FLAGS MATCHES "/W[0-4]")
## string(REGEX REPLACE "/W[0-4]" "/W4" CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS}")
## else()
## set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} /W4")
## endif()
Limpieza
Para limpiar el texto del archivo CMakeLists.txt, podemos realizar varias operaciones para eliminar elementos no deseados, como espacios en blanco adicionales, comentarios, líneas vacías o caracteres especiales. En este código utilizaremos: -¨grep¨ y una expresión regular para eliminar líneas que empiecen con ¨#¨ (comentarios) y líneas vacías. -Luego, eliminamos los espacios en blanco adicionales dentro del texto para dejar solo un espacio entre palabras. -Finalmente, mostramos el texto limpio en la consola de R.
library(httr)
# URL del archivo de texto
url <- "https://raw.githubusercontent.com/d99kris/rapidcsv/master/CMakeLists.txt"
# Realizar la solicitud GET para obtener el contenido del archivo
respuesta <- GET(url)
# Verificar el estado de la respuesta
if (http_type(respuesta) == "text/plain") {
# Leer el contenido del archivo
contenido <- content(respuesta, as = "text")
# Eliminar líneas vacías y comentarios
lineas_limpias <- grep("^[^#\\s]+", strsplit(contenido, "\n")[[1]], value = TRUE)
# Eliminar espacios en blanco adicionales
texto_limpio <- gsub("\\s+", " ", lineas_limpias)
# Mostrar el texto limpio
cat(texto_limpio, sep = "\n")
} else {
cat("No se pudo obtener el archivo de texto.")
}
## cmake_minimum_required(VERSION 3.1 FATAL_ERROR)
## project(rapidcsv VERSION 1.0 LANGUAGES CXX)
## if(MSVC)
## if(CMAKE_CXX_FLAGS MATCHES "/W[0-4]")
## string(REGEX REPLACE "/W[0-4]" "/W4" CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS}")
## else()
## set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} /W4")
## endif()
## add_compile_options("/utf-8")
## else()
## set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -g -Wall -Wextra -Wpedantic -Wshadow -Wpointer-arith \
## -Wcast-qual -Wno-missing-braces -Wswitch-default -Wcast-align \
## -Wunreachable-code -Wundef -Wuninitialized -Wold-style-cast \
## -Wsign-conversion -Weffc++")
## endif()
## if((EXISTS "${CMAKE_SOURCE_DIR}/.svn") OR (EXISTS "${CMAKE_SOURCE_DIR}/.git"))
## set(DEFAULT_BUILD_TYPE "Debug")
## endif()
## if(NOT CMAKE_BUILD_TYPE AND NOT CMAKE_CONFIGURATION_TYPES)
## message(STATUS "Using build type '${DEFAULT_BUILD_TYPE}' (default).")
## set(CMAKE_BUILD_TYPE "${DEFAULT_BUILD_TYPE}")
## else()
## message(STATUS "Using build type '${CMAKE_BUILD_TYPE}'.")
## endif()
## add_library(rapidcsv INTERFACE)
## target_include_directories(rapidcsv INTERFACE src)
## option(RAPIDCSV_BUILD_TESTS "Build tests" OFF)
## message(STATUS "Build tests: ${RAPIDCSV_BUILD_TESTS}")
## if(RAPIDCSV_BUILD_TESTS)
## # Test init
## include(CTest)
## enable_testing()
## # Ccache
## find_program(CCACHE_PROGRAM ccache)
## if(CCACHE_PROGRAM)
## message(STATUS "Found ccache")
## set_property(GLOBAL PROPERTY RULE_LAUNCH_COMPILE "${CCACHE_PROGRAM}")
## endif()
## # Enable codecvt tests if supported
## if (CMAKE_CXX_STANDARD VERSION_LESS "17")
## include(CheckIncludeFileCXX)
## check_include_file_cxx(codecvt HAS_CODECVT)
## if(HAS_CODECVT)
## target_compile_definitions(rapidcsv INTERFACE HAS_CODECVT)
## endif()
## else()
## message(STATUS "Skip check for C++ include codecvt - C++${CMAKE_CXX_STANDARD}")
## endif()
## # Test macro add_perf_test
## macro(add_perf_test testname)
## if(CMAKE_BUILD_TYPE MATCHES "Release")
## FILE(GLOB sources tests/${testname}*.cpp)
## add_executable(${testname} ${sources})
## add_test(NAME ${testname} COMMAND "${PROJECT_BINARY_DIR}/${testname}")
## target_link_libraries(${testname} PUBLIC rapidcsv)
## endif()
## endmacro(add_perf_test)
## # Test macro add_unit_test
## macro(add_unit_test testname)
## if(CMAKE_BUILD_TYPE MATCHES "Debug")
## FILE(GLOB sources tests/${testname}*.cpp)
## add_executable(${testname} ${sources})
## add_test(NAME ${testname} COMMAND "${PROJECT_BINARY_DIR}/${testname}")
## target_link_libraries(${testname} PUBLIC rapidcsv)
## endif()
## endmacro(add_unit_test)
## # Unit tests
## add_unit_test(test001)
## add_unit_test(test002)
## add_unit_test(test003)
## add_unit_test(test004)
## add_unit_test(test005)
## add_unit_test(test006)
## add_unit_test(test007)
## add_unit_test(test008)
## add_unit_test(test009)
## add_unit_test(test010)
## add_unit_test(test011)
## add_unit_test(test012)
## add_unit_test(test013)
## add_unit_test(test014)
## add_unit_test(test015)
## add_unit_test(test016)
## add_unit_test(test017)
## add_unit_test(test018)
## add_unit_test(test019)
## add_unit_test(test020)
## add_unit_test(test021)
## add_unit_test(test022)
## add_unit_test(test023)
## add_unit_test(test024)
## add_unit_test(test025)
## add_unit_test(test026)
## add_unit_test(test027)
## add_unit_test(test028)
## add_unit_test(test029)
## add_unit_test(test030)
## add_unit_test(test031)
## add_unit_test(test032)
## add_unit_test(test033)
## add_unit_test(test034)
## add_unit_test(test035)
## add_unit_test(test036)
## add_unit_test(test037)
## add_unit_test(test038)
## add_unit_test(test039)
## add_unit_test(test040)
## add_unit_test(test041)
## add_unit_test(test042)
## add_unit_test(test043)
## add_unit_test(test044)
## add_unit_test(test045)
## add_unit_test(test046)
## add_unit_test(test047)
## add_unit_test(test048)
## add_unit_test(test049)
## add_unit_test(test050)
## add_unit_test(test051)
## add_unit_test(test052)
## add_unit_test(test053)
## add_unit_test(test054)
## add_unit_test(test055)
## add_unit_test(test056)
## if(HAS_CODECVT)
## add_unit_test(test057)
## add_unit_test(test058)
## add_unit_test(test059)
## add_unit_test(test060)
## endif()
## add_unit_test(test061)
## add_unit_test(test062)
## add_unit_test(test063)
## add_unit_test(test064)
## add_unit_test(test065)
## add_unit_test(test066)
## add_unit_test(test067)
## add_unit_test(test068)
## add_unit_test(test069)
## add_unit_test(test070)
## add_unit_test(test071)
## add_unit_test(test072)
## add_unit_test(test073)
## add_unit_test(test074)
## add_unit_test(test075)
## add_unit_test(test076)
## add_unit_test(test077)
## add_unit_test(test078)
## add_unit_test(test079)
## add_unit_test(test080)
## add_unit_test(test081)
## add_unit_test(test082)
## add_unit_test(test083)
## add_unit_test(test084)
## if(HAS_CODECVT)
## add_unit_test(test085)
## endif()
## add_unit_test(test086)
## add_unit_test(test087)
## add_unit_test(test088)
## add_unit_test(test089)
## add_unit_test(test090)
## add_unit_test(test091)
## add_unit_test(test092)
## add_unit_test(test093)
## add_unit_test(test094)
## add_unit_test(test095)
## # perf tests
## add_perf_test(ptest001)
## add_perf_test(ptest002)
## # Examples
## # Test macro add_example
## macro(add_example testname)
## if(CMAKE_BUILD_TYPE MATCHES "Debug")
## add_executable(${testname} examples/${testname}.cpp)
## target_link_libraries(${testname} PUBLIC rapidcsv)
## endif()
## endmacro(add_example)
## add_example(ex001 examples/ex001.cpp)
## add_example(ex002 examples/ex002.cpp)
## add_example(ex003 examples/ex003.cpp)
## add_example(ex004 examples/ex004.cpp)
## add_example(ex005 examples/ex005.cpp)
## add_example(ex006 examples/ex006.cpp)
## add_example(ex007 examples/ex007.cpp)
## add_example(ex008 examples/ex008.cpp)
## add_example(ex009 examples/ex009.cpp)
## endif()
## if(CMAKE_SOURCE_DIR STREQUAL PROJECT_SOURCE_DIR)
## message(STATUS "Install/uninstall targets enabled.")
## # Install
## install(FILES ${CMAKE_CURRENT_SOURCE_DIR}/src/rapidcsv.h DESTINATION include)
## # Uninstall
## add_custom_target(uninstall COMMAND "${CMAKE_COMMAND}" -E remove "${CMAKE_INSTALL_PREFIX}/include/rapidcsv.h"
## )
## else()
## message(STATUS "Install/uninstall targets disabled.")
## endif()
Más procesamientos
El siguiente código realiza las siguientes operaciones:
-Obtiene el contenido del archivo CMakeLists.txt desde la URL.
-Limpia el texto eliminando líneas vacías y comentarios.
-Extrae todas las palabras del texto.
-Cuenta la frecuencia de cada palabra y muestra las 10 palabras más frecuentes.
library(httr)
library(stringr)
# URL del archivo de texto
url <- "https://raw.githubusercontent.com/d99kris/rapidcsv/master/CMakeLists.txt"
# Realizar la solicitud GET para obtener el contenido del archivo
respuesta <- GET(url)
# Verificar el estado de la respuesta
if (http_type(respuesta) == "text/plain") {
# Leer el contenido del archivo
contenido <- content(respuesta, as = "text")
# Eliminar líneas vacías y comentarios
lineas_limpias <- grep("^[^#\\s]+", strsplit(contenido, "\n")[[1]], value = TRUE)
# Obtener todas las palabras del texto
palabras <- unlist(str_extract_all(paste(lineas_limpias, collapse = " "), "\\w+"))
# Convertir a minúsculas y contar la frecuencia de palabras
frecuencia_palabras <- table(tolower(palabras))
# Mostrar las 10 palabras más frecuentes
palabras_mas_frecuentes <- head(sort(frecuencia_palabras, decreasing = TRUE), 10)
print(palabras_mas_frecuentes)
# Realizar otras operaciones de procesamiento de texto según sea necesario
} else {
cat("No se pudo obtener el archivo de texto.")
}
##
## add_unit_test testname if endif add_example
## 98 16 15 14 12
## cpp examples rapidcsv cmake_cxx_flags message
## 12 11 9 7 7
En virtud de lo presentado hasta aquí,notamos que R se destaca como un lenguaje altamente versátil para el análisis de datos, siendo capaz de manejar una amplia variedad de tipos de datos, desde números, imagenes hasta texto y valores lógicos. Desde la importación de datos mediante funciones como read.csv() hasta la manipulación de DataFrames con métodos como slice() y colnames(), R ofrece herramientas potentes para explorar, limpiar y procesar conjuntos de datos, fundamentales en proyectos de análisis. Su flexibilidad en la manipulación de datos estructurados y técnicas de procesamiento de texto permite un enfoque integral para analizar datos de manera exhaustiva, adaptándose a diversas necesidades analíticas.