Skip to Content
Course content

151: R vs Python: When to Choose Which

Click on the "Edit" button in the top corner of the screen to edit your slide content.

I get asked this all the time: "I know both, so which one should I actually use?" It’s a tricky question because the answer isn't about which language is "better," but about where you are in your workflow. I've spent the last decade jumping between these two, and I've developed a rule of thumb: use R to find the answer, and use Python to deploy the answer.

The Battle of the Quick Insight

Let's look at a real scenario. Suppose I have a dataset of city-wide air quality indices over a year. I want to see if there's a correlation between humidity and particulate matter, but I need to see it broken down by city to make sure one outlier city isn't skewing my whole result. This is a classic "exploratory" task.

My instinct as a software engineer is often to reach for Python. I love the ecosystem. I started by loading the data into a Pandas DataFrame and trying to build a faceted scatter plot using Seaborn. It looks something like this:

import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt

df = pd.read_csv("air_quality.csv")
g = sns.FacetGrid(df, col="city", col_wrap=4)
g.map(sns.scatterplot, "humidity", "pm25")
plt.show()

Wrestling with the Plotting Boilerplate

Here is where I made my mistake. I spent the next thirty minutes fighting with the Matplotlib backend to get the axis labels to stop overlapping and to move the legend so it didn't cover the data points. I was writing lines of code that had nothing to do with air quality and everything to do with the "plumbing" of the graph.

I stopped and realized I was treating this like a software project rather than a data question. When you're in the "I wonder if X affects Y" phase, the friction of the tool matters. I was using a hammer to do the job of a scalpel.

Letting R Do the Heavy Lifting

I pivoted to R, specifically using the Tidyverse. Because R was built by statisticians for statisticians, the "grammar of graphics" is baked into the DNA of the language. I could achieve that same faceted plot, with better defaults and cleaner labels, in a few lines of piped code:

library(tidyverse)

air_data <- read_csv("air_quality.csv")

air_data %>%
  ggplot(aes(x = humidity, y = pm25)) +
  geom_point(alpha = 0.5) +
  facet_wrap(~city) +
  theme_minimal() +
  labs(title = "Humidity vs PM2.5 by City")

Notice the difference? In R, the code reads like a sentence: "Take the data, map the aesthetics, add points, wrap it by city, and make it look clean." I didn't have to manage a "Figure" object or "Axis" objects separately. I found the insight in two minutes instead of twenty.

Drawing the Line for Production

Now, here is the pivot. If my boss then said, "This is great, now build a real-time dashboard that pulls this data from an API every hour and alerts the city manager via Slack," I would immediately switch back to Python.

  • Choose R when: You are doing heavy statistical analysis, creating publication-quality visualizations, or exploring a dataset where you don't yet know what the "answer" is.
  • Choose Python when: Your analysis needs to live inside a larger software application, you're building a machine learning pipeline for production, or you need to integrate with a wide array of non-data web services.

I don't view them as competitors. I view R as my laboratory and Python as my factory. You do the messy, creative, iterative work in the lab, and once you have a proven formula, you move it to the factory for scale.




πŸ“‹ Practical Task

Refactoring a Python Analysis into a Tidyverse Pipeline

You have been handed a snippet of Python code used by a teammate to analyze a dataset of employee salaries. The Python code is functional but verbose, and the team wants to move the exploratory phase of this project into R to speed up their iterations.

The Python Code:

import pandas as pd
import seaborn as sns

df = pd.read_csv("salaries.csv")
# Filter for employees with more than 5 years experience
filtered_df = df[df['experience'] > 5]
# Create a boxplot of salary grouped by department
sns.boxplot(x='department', y='salary', data=filtered_df)

Your Task:
Rewrite this logic in R using the tidyverse (specifically dplyr and ggplot2). Your code should perform the same filtering and create the same visualization. Ensure you use the pipe operator (%>%) to keep the workflow concise.

Rating
0 0

There are no comments for now.

to be the first to leave a comment.