⚠️ Advertencia crítica antes de correr cualquier script
No ejecutes scripts de R contra archivos oficiales, bases de datos reales, carpetas institucionales, SQL Server, Access, APIs internas o datasets sensibles sin autorización formal.
R puede transformar, resumir, modelar y visualizar miles o millones de registros rápidamente. Un análisis mal probado puede producir conclusiones incorrectas, sobrescribir archivos, exponer datos sensibles o afectar decisiones de BI, auditoría, presupuesto o producción.
Regla obligatoria del training: primero se trabaja con data sintética, luego con una copia controlada, después se valida el resultado, y solo entonces se considera usar datos reales siguiendo permisos, backup, change control, data governance y protocolos de ciberseguridad.
- Permisos: usa solamente archivos y fuentes donde tengas autorización explícita.
- Backups: nunca sobrescribas data original sin una copia recuperable.
- Data governance: respeta privacidad, controles de acceso y clasificación de datos.
- Producción: nunca conectes scripts a fuentes reales sin revisión, aprobación y plan de reversa.
⚠️ Critical warning before running any script
Do not run R scripts against official files, real databases, institutional folders, SQL Server, Access, internal APIs, or sensitive datasets without formal authorization.
R can transform, summarize, model, and visualize thousands or millions of records quickly. A poorly tested analysis can produce wrong conclusions, overwrite files, expose sensitive data, or affect BI, audit, budget, or production decisions.
Mandatory training rule: start with synthetic data, then use a controlled copy, validate the result, and only then consider real data while following permissions, backups, change control, data governance, and cybersecurity protocols.
- Permissions: use only files and sources where you have explicit authorization.
- Backups: never overwrite original data without a recoverable copy.
- Data governance: respect privacy, access controls, and data classification.
- Production: never connect scripts to real sources without review, approval, and rollback planning.
Objetivo del Topic 18
Convierte transacciones diarias en una vista mensual para detectar crecimiento, caída o estacionalidad.
Topic 18 Objective
Convert daily transactions into a monthly view to detect growth, decline, or seasonality.
Ruta de trabajo
Todo se ejecuta dentro de una carpeta controlada:
Working folder
Everything runs inside a controlled folder:
base_path <- file.path(Sys.getenv("USERPROFILE"), "Documents", "AI Practical Training", "R", "Topic 18")Qué vamos a aprender
- Crear data sintética controlada.
- Leer y transformar datos en R.
- Aplicar una regla de análisis, limpieza o validación.
- Exportar resultados para revisión.
- Verificar el resultado antes de usar datos reales.
What you will learn
- Create controlled synthetic data.
- Read and transform data in R.
- Apply an analysis, cleaning, or validation rule.
- Export results for review.
- Verify the result before using real data.
Script 1 — Crear data sintética
Este script prepara datos de práctica para ejecutar el ejercicio sin tocar información real.
Script 1 — Create synthetic data
This script prepares practice data to run the exercise without touching real information.
# R Topic 18 - Script 1
base_path <- file.path(Sys.getenv("USERPROFILE"), "Documents", "AI Practical Training", "R", "Topic 18")
data_path <- file.path(base_path, "Data"); dir.create(data_path, recursive = TRUE, showWarnings = FALSE)
data <- data.frame(transaction_date=c("2026-01-05","2026-01-20","2026-02-10","2026-03-01","2026-03-15"), amount=c(100,150,200,300,250))
write.csv(data, file.path(data_path,"daily_transactions.csv"), row.names=FALSE)
print(data)Script 2 — Ejecutar la acción principal
Este script aplica la lógica central del topic y genera el resultado principal del ejercicio.
Script 2 — Run the main action
This script applies the core topic logic and generates the main result of the exercise.
# R Topic 18 - Script 2
library(readr); library(dplyr); library(lubridate); library(ggplot2)
base_path <- file.path(Sys.getenv("USERPROFILE"), "Documents", "AI Practical Training", "R", "Topic 18")
data_path <- file.path(base_path, "Data")
data <- read_csv(file.path(data_path,"daily_transactions.csv"), show_col_types=FALSE)
monthly_trend <- data %>% mutate(date_clean=ymd(transaction_date), month_start=floor_date(date_clean, "month")) %>% group_by(month_start) %>% summarise(total_amount=sum(amount, na.rm=TRUE), .groups="drop")
write.csv(monthly_trend, file.path(data_path,"monthly_trend.csv"), row.names=FALSE)
plot <- ggplot(monthly_trend, aes(month_start, total_amount)) + geom_line() + geom_point() + labs(title="Monthly Trend")
ggsave(file.path(data_path,"monthly_trend.png"), plot, width=8, height=5)
print(monthly_trend)Script 3 — Verificar o reportar resultados
Este script confirma el resultado final o genera evidencia para revisión.
Script 3 — Verify or report results
This script confirms the final result or generates evidence for review.
# R Topic 18 - Script 3
library(readr)
base_path <- file.path(Sys.getenv("USERPROFILE"), "Documents", "AI Practical Training", "R", "Topic 18")
print(read_csv(file.path(base_path,"Data","monthly_trend.csv"), show_col_types=FALSE))
print(file.exists(file.path(base_path,"Data","monthly_trend.png")))Explicación simple del script
- base_path mantiene una ruta de práctica controlada.
- El Script 1 crea data sintética para evitar riesgos.
- El Script 2 aplica la lógica principal del topic.
- El Script 3 verifica resultados o deja evidencia.
- El resultado se guarda como CSV, imagen, Excel o reporte según el caso.
Simple script explanation
- base_path keeps a controlled practice path.
- Script 1 creates synthetic data to avoid risk.
- Script 2 applies the main topic logic.
- Script 3 verifies results or leaves evidence.
- The output is saved as CSV, image, Excel, or report depending on the case.
Ejemplo esperado
| Caso | Resultado |
|---|---|
| daily rows | monthly totals |
| line chart | trend view |
Expected example
| Case | Result |
|---|---|
| daily rows | monthly totals |
| line chart | trend view |
Conclusión
Convierte transacciones diarias en una vista mensual para detectar crecimiento, caída o estacionalidad.
Conclusion
Convert daily transactions into a monthly view to detect growth, decline, or seasonality.