Back to code R

Ventas, margen y participación por categoría en seis líneas

Con R base y sin paquetes: sumar por categoría, calcular margen y participación, y ordenar de mayor a menor.

This post is not in your language yet; you are seeing it in Spanish. The code is the same.

The problem

Te pasan las ventas del mes y la pregunta de siempre: qué categoría vende más, cuál deja más margen y cuánto pesa cada una. No hace falta instalar nada para contestar.

R
ventas <- data.frame(
  categoria = c("Bebidas", "Snacks", "Bebidas", "Limpieza", "Snacks", "Bebidas"),
  monto     = c(120.5, 80, 210.25, 150, 45.75, 99),
  costo     = c(70, 52, 130, 110, 30, 61)
)

resumen <- aggregate(cbind(monto, costo) ~ categoria, data = ventas, FUN = sum)
resumen$margen_pct <- round((resumen$monto - resumen$costo) / resumen$monto * 100, 1)
resumen$participacion <- round(resumen$monto / sum(resumen$monto) * 100, 1)
resumen <- resumen[order(-resumen$monto), ]

print(resumen, row.names = FALSE)

Why it is written this way

  1. aggregate con la fórmula cbind(monto, costo) ~ categoria suma las dos columnas por cada categoría de una vez.
  2. Las operaciones son vectorizadas: el margen de todas las categorías se calcula en una línea, sin bucle.
  3. order con el signo menos ordena de mayor a menor.
  4. Todo es R base: corre en cualquier instalación, sin tidyverse.
How to try it

Guardalo como resumen.R y corré: Rscript resumen.R. Para tus datos, reemplazá el data.frame por read.csv("ventas.csv").

Watch out

aggregate descarta en silencio las filas con NA en cualquiera de las columnas. Si tu archivo tiene vacíos, el total va a dar menos sin avisar: revisá con summary(ventas) antes.

Adapt it to your case with AI

The button copies this prompt with the code pasted below it. Replace the brackets with your own details and paste it into ChatGPT, Claude, Gemini or Copilot.

The prompt
Tengo este resumen de ventas por categoría en R base. Mis datos reales están en [ARCHIVO] con estas columnas: [COLUMNAS]. Adaptalo para leer el archivo, tratar los valores vacíos de forma explícita (decime cuántas filas quedan afuera y por qué), agregar la comparación contra [PERÍODO ANTERIOR] y exportar el resultado a CSV. Sin paquetes externos salvo que sea imprescindible, y decime cuál.

Example written and reviewed by hand.

Share

Comments

No comments yet. Yours can be the first.

Plain text only, no links. No email is requested. Comments are reviewed before they are published.

Did you adapt it to something of yours?

Tell me what you solved with it, or what it was missing.

Keep trying

More code

See all
Darinel Ortega Online · I reply during the day
Today
Hello. I'm not selling anything here: this is for exchanging knowledge about technology.
Write whatever you like — you can send text, images or documents. Messages reach my console and I reply from there.

An open conversation to share knowledge. Messages reach my console and I reply from there.

Let us book a conversation

Pick the day and time that work for you. Thirty minutes, no sales pitch.

Video call

For a video call, just ask for one here and I'll send you the session link.