Database Manipulation in R

1. OBJETIVES

1.1. Manipulating Vectors and Matrices in R.

1.2. Manipulating Databases in R.

2. Activities

2.1. Install and load the packages usingR and MASS

a) install.packages(“package”)
b) library(package)

2.2. brightness contain information on the brightness of 963 stars.

a) Represent these data employing a histogram and a superimposed density plot.
b) Graphically represent these data using a boxplot. Would you say that the data have “outliers”? What is the second smallest outlier?
c) We want to keep data that cannot be considered outliers. Create a new variable called brightness.without containing only the values without outliers.

2.3. UScereal contain information on the breakfast with cereals.

a) determine the relationship between
i. manufacturer & shelf.
ii. fat & vitamins.
iii. fat & shelf.
iv. carbohydrates & sugars.
v. fibre & manufacturer.
vi. sodium & sugars.

2.4. mammals contain information on relationship between body weight and brain weight of mammals.

a) What is the linear correlation between these variables?
b) plot the data
c) Transform the data using the log function and repeat the study. How do the results change?

2.5. emissions contain information on CO2 emissions data and gross domestic product for 26 countries

a) Study the relationship between the variables GDP, perCapita and CO2 of each country.
b) train a linear regression model to predict CO2 emissions from of the variables.
c) Identify the outliers and try to fit the model again without them.

2.6. Anorexia contain information on weight change in female patients.

a) What treatment was most effective?
b) How many patients gained and how many lost weight?

Respuestas

2.1. Instalación y carga de paquetes

install.packages(“UsingR”) install.packages(“MASS”) library(usingR) library(MASS)

2.2. Análisis de datos de brillo

Cargar datos

data(brightness, package=“UsingR”)

a) Histograma y densidad

hist(brightness, probability = TRUE, main = “Histogram of Brightness”) lines(density(brightness), col = “blue”)

b) Boxplot y detección de outliers

boxplot(brightness, main = “Boxplot of Brightness”) outliers <- boxplot.stats(brightness)$out second_smallest_outlier <- sort(outliers)[2]

c) Crear nueva variable sin outliers

brightness.without <- brightness[!brightness %in% outliers]

2.3. Análisis de datos de cereales

Cargar datos

data(UScereal, package=“MASS”)

Verificar la estructura de los datos

str(UScereal)

Eliminar filas con datos faltantes en manufacturer o shelf

clean_cereal <- UScereal[complete.cases(UScereal\(manufacturer, UScereal\)shelf), ]

Relación entre manufacturer y shelf

manufacturer_shelf_table <- table(clean_cereal\(manufacturer, clean_cereal\)shelf) manufacturer_shelf_table

Relación entre fat y vitamins

cor(clean_cereal\(fat, clean_cereal\)vitamins, use=“complete.obs”)

Relación entre fat y shelf

cor(clean_cereal\(fat, clean_cereal\)shelf, use=“complete.obs”)

Relación entre carbohydrates y sugars

cor(clean_cereal\(carbo, clean_cereal\)sugars, use=“complete.obs”)

Relación entre fibre y manufacturer

fibre_manufacturer_table <- table(clean_cereal\(fibre, clean_cereal\)manufacturer) fibre_manufacturer_table

Relación entre sodium y sugars

cor(clean_cereal\(sodium, clean_cereal\)sugars, use=“complete.obs”)

Análisis de datos Mamiferos

Cargar datos

data(mammals, package=“MASS”)

a) Correlación

cor(mammals\(body, mammals\)brain)

b) Gráfico de datos

plot(mammals\(body, mammals\)brain, main = “Peso Corporal vs Peso Cerebral”, xlab = “Peso Corporal”, ylab = “Peso Cerebral”)

c) Transformación logarítmica y repetición del análisis

mammals\(log_body <- log(mammals\)body) mammals\(log_brain <- log(mammals\)brain) cor(mammals\(log_body, mammals\)log_brain) plot(mammals\(log_body, mammals\)log_brain, main = “Log Peso Corporal vs Log Peso Cerebral”, xlab = “Log Peso Corporal”, ylab = “Log Peso Cerebral”)

2.5. Análisis de emisiones de CO2

Cargar datos

data(emissions, package=“MASS”)

a) Relación entre variables

pairs(~GDP + perCapita + CO2, data = emissions)

b) Modelo de regresión lineal

model <- lm(CO2 ~ GDP + perCapita, data = emissions) summary(model)

c) Identificación de outliers y ajuste del modelo

outliers <- which(abs(model\(residuals) > 2*sd(model\)residuals)) emissions_clean <- emissions[-outliers, ] model_clean <- lm(CO2 ~ GDP + perCapita, data = emissions_clean) summary(model_clean)

2.6. Análisis de datos de anorexia

Cargar datos

data(anorexia, package=“MASS”)

a) Tratamiento más efectivo

aggregate(Postwt ~ Treat, data = anorexia, mean)

b) Conteo de pacientes que ganaron o perdieron peso

table(anorexia\(Postwt > anorexia\)Prewt)

2.7. Prueba de normalidad y t-student

Generación de vectores

vec1 <- rnorm(50) vec2 <- rnorm(50)

a) Prueba de normalidad

shapiro.test(vec1) shapiro.test(vec2)

b) Prueba t-student

t.test(vec1, vec2)

2.8. Normalidad y diferencia significativa entre vectores

Generación de vectores

vec_norm <- rnorm(50) vec_binom <- rbinom(50, 1, 0.5)

a) Prueba de normalidad

shapiro.test(vec_norm) shapiro.test(vec_binom)

b) Prueba t-student

t.test(vec_norm, vec_binom)

2.9. Generación y análisis de valores

Generación de valores

values <- rnorm(100)

a) Histograma

hist(values, main = “Histograma de Valores Generados”)

b) Repetición del proceso

values2 <- rnorm(100) hist(values2, main = “Histograma de Valores Generados”)

c) Resumen de datos

summary(values)

2.10. Ejemplos prácticos con pwr.t.test

Investigación y ejemplos prácticos

library(pwr)

Ejemplo 1: T-test de dos muestras

pwr.t.test(n = 20, d = 0.5, sig.level = 0.05, power = 0.8, type = “two.sample”)

Ejemplo 2: T-test de una muestra

pwr.t.test(n = 20, d = 0.5, sig.level = 0.05, power = 0.8, type = “one.sample”)