CARGAR DATOS
setwd("/cloud/project")
datos<-read.csv("database.csv", header =TRUE,sep=",",dec=".")
CARGAR LIBRERIAS Y PACKETES
library(e1071)
library(PASWR)
## Loading required package: lattice
library(SmartEDA)
library(plotly)
## Loading required package: ggplot2
##
## Attaching package: 'plotly'
## The following object is masked from 'package:ggplot2':
##
## last_plot
## The following object is masked from 'package:stats':
##
## filter
## The following object is masked from 'package:graphics':
##
## layout
library(dplyr)
##
## Attaching package: 'dplyr'
## The following objects are masked from 'package:stats':
##
## filter, lag
## The following objects are masked from 'package:base':
##
## intersect, setdiff, setequal, union
library(ggplot2)
library(tidyverse)
## ── Attaching core tidyverse packages ──────────────────────── tidyverse 2.0.0 ──
## ✔ forcats 1.0.0 ✔ stringr 1.5.1
## ✔ lubridate 1.9.4 ✔ tibble 3.3.0
## ✔ purrr 1.1.0 ✔ tidyr 1.3.1
## ✔ readr 2.1.5
## ── Conflicts ────────────────────────────────────────── tidyverse_conflicts() ──
## ✖ dplyr::filter() masks plotly::filter(), stats::filter()
## ✖ dplyr::lag() masks stats::lag()
## ℹ Use the conflicted package (<http://conflicted.r-lib.org/>) to force all conflicts to become errors
MODELO N3 (EXPONENCIAL)
Diagrama de dispersion
plot(datos$City.MPG..FT1.,datos$Highway.MPG..FT1.)

x<-datos$City.MPG..FT1.
y<-datos$Highway.MPG..FT1.
plot(x,y)

min(y)
## [1] 9
y1<-log(y)
Circulo de la regresión
regresionExponencial<-lm(y1~x, na.action = na.omit)
regresionExponencial
##
## Call:
## lm(formula = y1 ~ x, na.action = na.omit)
##
## Coefficients:
## (Intercept) x
## 2.60271 0.03027
summary(regresionExponencial)
##
## Call:
## lm(formula = y1 ~ x, na.action = na.omit)
##
## Residuals:
## Min 1Q Median 3Q Max
## -2.33878 -0.08201 0.03053 0.10234 0.36426
##
## Coefficients:
## Estimate Std. Error t value Pr(>|t|)
## (Intercept) 2.6027077 0.0021995 1183.3 <2e-16 ***
## x 0.0302673 0.0001143 264.8 <2e-16 ***
## ---
## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
##
## Residual standard error: 0.1529 on 38111 degrees of freedom
## Multiple R-squared: 0.6478, Adjusted R-squared: 0.6478
## F-statistic: 7.011e+04 on 1 and 38111 DF, p-value: < 2.2e-16
Gráfica Modelo Exponencial
plot(x,y,col=5,pch=7,main = "Regresión Exponencial",
xlab="Consumo del Combutible Primario en Ciudad (MPG)",ylab="Consumo del Combutible Primario en Carretera (MPG) ")
curve(a*exp(b*x),from=0, to=100,add=T,col="red")

Test de bondad
R <- cor(x, y1, use = "complete.obs")
R
## [1] 0.8048827
R2<- R^2*100
R2
## [1] 64.78362
MODELO EXPONENCIAL MEJORADO
Definir tus variables (ajústalas si los nombres en tu dataset son
distintos)
x <- datos$City.MPG..FT1. # Variable independiente
y <- datos$Highway.MPG..FT1. # Variable dependiente
Crear un data frame base
datos <- data.frame(x, y)
Filtrar rango general de interés
datos <- datos %>%
filter(x >= 6, x <= 150, !is.na(x), !is.na(y))
Valor de corte (donde el modelo exponencial deja de funcionar
bien)
x_límite_funcional <- 30
Dividir en tramos
datos_tramo1 <- datos %>% filter(x <= x_límite_funcional)
datos_tramo2 <- datos %>% filter(x > x_límite_funcional)
MODELO EXPONENCIAL (TRAMO 1)
Parámetros del modelo exponencial
a1 <- exp(beta0)
b1 <- beta1
MODELO LINEAL (TRAMO 2)
modelo_tramo2 <- lm(y ~ x, data = datos_tramo2)
Gráfico base con puntos originales
plot(x, y, pch = 16, col = rgb(0, 0, 1, 0.1),
main = "Modelos por tramos según City (MPG)",
xlab = "Consumo de combustible en ciudad (MPG)",
ylab = "Consumo de combustible en carretera (MPG)")
curve(a1 * exp(b1 * x), from = min(datos_tramo1$x), to = max(datos_tramo1$x),
add = TRUE, col = "red", lwd = 2)
abline(modelo_tramo2, col = "darkgreen", lwd = 2)
abline(v = x_límite_funcional, col = "purple", lty = 2)
legend("bottomright", legend = c("Exponencial (x ≤ 30)", "Lineal (x > 30)"),
col = c("red", "darkgreen"), lwd = 2, bty = "n")

Test de Bondad
R <- cor(x, y, use = "complete.obs")
R
## [1] 0.9317386
R2<- R^2*100
R2
## [1] 86.81368
REGRESIÓN LOGARÍTMICA
Cargar datos
datos<-read.csv("database.csv", header =TRUE,sep=",",dec=".")
Eliminar NA y valores inválidos
datos_filtrados <- na.omit(data.frame(x = x, y = y))
datos_filtrados <- subset(datos_filtrados, x > 0 & x != -1 & y != -1)
Asegurarse de que ‘x’ sea numérico
datos_filtrados$x <- as.numeric(datos_filtrados$x)
Verificar si hay valores no numéricos
if (any(is.na(datos_filtrados$x))) {
warning("Existen valores no numéricos en la columna 'x'. Estos se han convertido a NA.")
}
Crear columna log(x)
datos_filtrados$log_x <- log(datos_filtrados$x)
Ajustar modelo logarítmico
modelo <- lm(y ~ log_x, data = datos_filtrados)
Coeficientes
a <- coef(modelo)[1]
b <- coef(modelo)[2]
Secuencia para suavizar la curva
x_seq <- seq(min(datos_filtrados$x), max(datos_filtrados$x), length.out = 200)
y_pred <- a + b * log(x_seq)
Test de Bondad
R <- cor(datos_filtrados$y, predict(modelo))
R2 <- summary(modelo)$r.squared * 100
Graficar datos y curva ajustada
plot(
datos_filtrados$x, datos_filtrados$y,
main = "Regresión Logarítmica: Cilindros vs Economía",
xlab = "Cilindros del motor (#)", ylab = "Puntaje de economía de combustible (PTS)",
pch = 19, col = "steelblue"
)
lines(x_seq, y_pred, col = "darkred", lwd = 2)
legend(
"topright",
legend = c(
sprintf("R = %.4f", R),
sprintf("R² = %.2f%%", R2)
),
bty = "n",
text.col = "black"
)

REGRESIÓN LOGARÍTMICA MEJORADO
Variables
x <- datos$Engine.Cylinders
y <- datos$Fuel.Economy.Score
Eliminar NA y valores inválidos (-1)
datos_filtrados <- na.omit(data.frame(x = x, y = y))
datos_filtrados <- subset(datos_filtrados, x > 0 & x != -1 & y != -1)
Agrupar por cilindros y sacar promedio del Fuel Economy Score
library(dplyr)
datos_prom <- datos_filtrados %>%
group_by(x) %>%
summarise(y = mean(y))
Crear columna log(x)
datos_prom$log_x <- log(datos_prom$x)
Ajustar modelo logarítmico sobre promedios
modelo <- lm(y ~ log_x, data = datos_prom)
Coeficientes
a <- coef(modelo)[1]
b <- coef(modelo)[2]
Test de Bondad
R <- cor(datos_prom$log_x, datos_prom$y)
R2 <- summary(modelo)$r.squared * 100
Crear curva suavizada
x_seq <- seq(min(datos_prom$x), max(datos_prom$x), length.out = 200)
y_pred <- a + b * log(x_seq)