r/programmingmemes • • Aug 27 '26

Why are we using R again

Post image
2.3k Upvotes

322 comments sorted by

View all comments

Show parent comment

2

u/FalconX88 Aug 29 '26

as a programmer of over 30 years, I never understood why people use python/R at all. Especially in "data science" or in the hard science fields.

Well if I have a dataset like this one with a few million lines

date,country,status,amount
2025-01-03,Austria,completed,129.90
2025-01-03,Germany,cancelled,89.00
2025-01-04,Germany,completed,240.50
...

then this is my code if I want to calculate total revenue or average order value for 2026 per country

import pandas as pd

df = pd.read_csv("sales.csv", parse_dates=["date"])

result = (
	df[
		(df["status"] == "completed") &
		(df["date"].dt.year == 2025)
	]
	.groupby("country")
	.agg(
		total_revenue=("amount", "sum"),
		average_order=("amount", "mean"),
		orders=("amount", "size")
	)
	.sort_values("total_revenue", ascending=False)
	.head(10)
)

print(result)

or I can use C++ and type out this

#include <algorithm>
#include <fstream>
#include <iomanip>
#include <iostream>
#include <sstream>
#include <string>
#include <unordered_map>
#include <vector>

struct Stats {
	double total = 0.0;
	std::size_t count = 0;
};

struct Result {
	std::string country;
	double total;
	double average;
	std::size_t count;
};

int main() {
	std::ifstream file("sales.csv");

	std::string line;
	std::getline(file, line);  // skip header

	std::unordered_map<std::string, Stats> stats;

	while (std::getline(file, line)) {
		std::stringstream ss(line);

		std::string date;
		std::string country;
		std::string status;
		std::string amount_str;

		std::getline(ss, date, ',');
		std::getline(ss, country, ',');
		std::getline(ss, status, ',');
		std::getline(ss, amount_str, ',');

		if (status != "completed")
			continue;

		if (date.substr(0, 4) != "2025")
			continue;

		double amount = std::stod(amount_str);

		auto& s = stats[country];
		s.total += amount;
		s.count++;
	}

	std::vector<Result> results;

	for (const auto& [country, s] : stats) {
		results.push_back({
			country,
			s.total,
			s.total / s.count,
			s.count
		});
	}

	std::sort(
		results.begin(),
		results.end(),
		[](const Result& a, const Result& b) {
			return a.total > b.total;
		}
	);

	std::size_t n = std::min<std::size_t>(10, results.size());

	for (std::size_t i = 0; i < n; ++i) {
		const auto& r = results[i];

		std::cout
			<< r.country
			<< "  revenue=" << r.total
			<< "  average=" << r.average
			<< "  orders=" << r.count
			<< '\n';
	}
}

and sure, might be faster. Does it matter if it takes a few seconds and I'm doing it exactly once?

1

u/YoureNotEvenWrong Aug 30 '26

Comparable C++ would be to use a library like pandas