En R, un objeto es una estructura fundamental que almacena datos, resultados o funciones. Todo en R es un objeto, desde un simple número hasta un complejo modelo estadístico.
# Crear un vector numérico
vector_a <- c(20, 51, 84, 6, 0, 3)
# Crear un data frame
a_df <- data.frame(
estudiante = c("Ana", "Bruno", "Carla", "Daniel", "Enrique"),
n_hermanos = c(1, 13, 6, 0, 3)
)
# Crear una lista
lista_a <- list(vector = vector_a, df = a_df)
# Crear una función
a_funcion <- function(x) { x^2 }
# Vector
tercer_elemento <- vector_a[3]
# Data frame
columna_estudiante <- a_df$estudiante
primera_fila <- a_df[1, ]
columna_n_hermanos <- a_df[, "n_hermanos"]
# Lista
elemento_df <- lista_a$df
primer_elemento_lista <- lista_a[[1]]
# Cambiar un valor en un vector
vector_a[2] <- 10
# Agregar columna a un data frame
a_df$ciudad <- c("Madrid", "La Argentina", "Valencia", "Florencia", "Neiva")
# Eliminar un elemento de una lista
lista_a$vector <- NULL
# Aritméticas
suma_vector <- sum(vector_a)
media_n_hermanos <- mean(a_df$n_hermanos)
# Funciones aplicadas
longitud_lista <- lapply(lista_a, length)
# Transformaciones
a_df$hermanos_mayor_5 <- ifelse(a_df$n_hermanos > 5, "Sí", "No")
# Imprimir el data frame
print(a_df)
## estudiante n_hermanos ciudad hermanos_mayor_5
## 1 Ana 1 Madrid No
## 2 Bruno 13 La Argentina Sí
## 3 Carla 6 Valencia Sí
## 4 Daniel 0 Florencia No
## 5 Enrique 3 Neiva No
america <- c("Colombia", "Bolivia", "Argentina", "Ecuador", "Perú")
print(america[3])
## [1] "Argentina"
print(america[5])
## [1] "Perú"
resultado_logico <- (5 >= 3) & (4 == 2 + 2) | (7 < 1)
print(resultado_logico)
## [1] TRUE
cantidad1 <- 5
print(class(cantidad1))
## [1] "numeric"
# Creación del dataframe
empresa <- data.frame(
rol = c("jefe_administrativo", "supervisor", "almacenista", "secretario", "servicios_g"),
horas_trabajo = c(25, 34, 28, 22, 45),
permisos = c(4, 1, 2, 3, 0)
)
# Imprimir el dataframe
print(empresa)
## rol horas_trabajo permisos
## 1 jefe_administrativo 25 4
## 2 supervisor 34 1
## 3 almacenista 28 2
## 4 secretario 22 3
## 5 servicios_g 45 0
# Importar datos desde un archivo CSV
# empresa_importada <- read.csv("datos_empresa.csv")
# print(empresa_importada)
# Exportar el dataframe a un archivo CSV
# write.csv(empresa, "empresa_exportada.csv", row.names = FALSE)
# Recodificar la columna 'rol'
empresa$rol_recodificado <- ifelse(empresa$rol == "jefe_administrativo", "Jefe",
ifelse(empresa$rol == "supervisor", "Supervisor",
ifelse(empresa$rol == "almacenista", "Almacenista",
ifelse(empresa$rol == "secretario", "Secretario", "Servicios"))))
# Imprimir el dataframe con la nueva columna
print(empresa)
## rol horas_trabajo permisos rol_recodificado
## 1 jefe_administrativo 25 4 Jefe
## 2 supervisor 34 1 Supervisor
## 3 almacenista 28 2 Almacenista
## 4 secretario 22 3 Secretario
## 5 servicios_g 45 0 Servicios
library(ggplot2)
## Warning: package 'ggplot2' was built under R version 4.4.3
library(dplyr)
## Warning: package 'dplyr' was built under R version 4.4.3
set.seed(123)
data <- data.frame(
grupo = rep(c("A", "B"), each = 50),
valor = c(rnorm(50, mean = 5, sd = 1), rnorm(50, mean = 7, sd = 1.5))
)
resumen <- summary(data)
print(resumen)
## grupo valor
## Length:100 Min. : 3.033
## Class :character 1st Qu.: 4.790
## Mode :character Median : 5.952
## Mean : 6.127
## 3rd Qu.: 7.207
## Max. :10.281
ggplot(data, aes(x = grupo, y = valor)) +
geom_boxplot() +
labs(title = "Boxplot de Valores por Grupo", x = "Grupo", y = "Valor")
prueba_t <- t.test(valor ~ grupo, data = data)
print(prueba_t)
##
## Welch Two Sample t-test
##
## data: valor by grupo
## t = -9.4004, df = 86.454, p-value = 7.187e-15
## alternative hypothesis: true difference in means between group A and group B is not equal to 0
## 95 percent confidence interval:
## -2.647288 -1.723130
## sample estimates:
## mean in group A mean in group B
## 5.034404 7.219612
data_cor <- data.frame(
x = rnorm(100),
y = rnorm(100)
)
correlacion <- cor(data_cor$x, data_cor$y)
print(paste("Correlación entre x e y:", correlacion))
## [1] "Correlación entre x e y: 0.0305790307587923"
modelo <- lm(valor ~ grupo, data = data)
summary(modelo)
##
## Call:
## lm(formula = valor ~ grupo, data = data)
##
## Residuals:
## Min 1Q Median 3Q Max
## -3.6834 -0.7112 -0.0651 0.6866 3.0614
##
## Coefficients:
## Estimate Std. Error t value Pr(>|t|)
## (Intercept) 5.0344 0.1644 30.63 < 2e-16 ***
## grupoB 2.1852 0.2325 9.40 2.42e-15 ***
## ---
## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
##
## Residual standard error: 1.162 on 98 degrees of freedom
## Multiple R-squared: 0.4742, Adjusted R-squared: 0.4688
## F-statistic: 88.37 on 1 and 98 DF, p-value: 2.424e-15
ggplot(data, aes(x = grupo, y = valor)) +
geom_point() +
geom_smooth(method = "lm", se = FALSE, color = "blue") +
labs(title = "Regresión Lineal de Valores por Grupo", x = "Grupo", y = "Valor")
## `geom_smooth()` using formula = 'y ~ x'
faithful
data("faithful")
plot(faithful$waiting, faithful$eruptions,
main = "Duración de Erupciones vs Tiempo de Espera",
xlab = "Tiempo de espera (minutos)",
ylab = "Duración de la erupción (minutos)",
pch = 19, col = "blue")
modelo <- lm(eruptions ~ waiting, data = faithful)
summary(modelo)
##
## Call:
## lm(formula = eruptions ~ waiting, data = faithful)
##
## Residuals:
## Min 1Q Median 3Q Max
## -1.29917 -0.37689 0.03508 0.34909 1.19329
##
## Coefficients:
## Estimate Std. Error t value Pr(>|t|)
## (Intercept) -1.874016 0.160143 -11.70 <2e-16 ***
## waiting 0.075628 0.002219 34.09 <2e-16 ***
## ---
## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
##
## Residual standard error: 0.4965 on 270 degrees of freedom
## Multiple R-squared: 0.8115, Adjusted R-squared: 0.8108
## F-statistic: 1162 on 1 and 270 DF, p-value: < 2.2e-16
abline(modelo, col = "red")
shapiro.test(faithful$eruptions)
##
## Shapiro-Wilk normality test
##
## data: faithful$eruptions
## W = 0.84592, p-value = 9.036e-16
shapiro.test(faithful$waiting)
##
## Shapiro-Wilk normality test
##
## data: faithful$waiting
## W = 0.92215, p-value = 1.015e-10
cor.test(faithful$eruptions, faithful$waiting, method = "pearson")
##
## Pearson's product-moment correlation
##
## data: faithful$eruptions and faithful$waiting
## t = 34.089, df = 270, p-value < 2.2e-16
## alternative hypothesis: true correlation is not equal to 0
## 95 percent confidence interval:
## 0.8756964 0.9210652
## sample estimates:
## cor
## 0.9008112
Tenemos: p-value < 2.2e-16 < 0.05 -> Es menor que 0.05, entonces, rechazamos la H₀ y aceptamos Hₐ, por lo tanto, existe una correlación entre la duración de la erupción y el tiempo de espera hasta que haya otra erupción. cor= 0.9008112 > 0.8 -> Es mayor que 0.8, entonces decimos que hay una correlación positiva fuerte, esto quiere decir que, a mayor tiempo de espera habrá un mayor duración de erupción