R vs Python: A Basic Language Comparison

Overview

This notebook provides a side-by-side comparison of fundamental programming concepts in R and Python. Both are powerful languages for data science, but they differ in syntax, philosophy, and idioms.


1. Variables & Data Types

R

# Assignment
x <- 42L          # integer
y <- 3.14         # double
name <- "Alice"   # character
flag <- TRUE      # logical

# Check types
class(x)
[1] "integer"
class(y)
[1] "numeric"
class(name)
[1] "character"
class(flag)
[1] "logical"

Python

# Assignment
x = 42            # int
y = 3.14          # float
name = "Alice"    # str
flag = True       # bool

# Check types
print(type(x))
<class 'int'>
print(type(y))
<class 'float'>
print(type(name))
<class 'str'>
print(type(flag))
<class 'bool'>

Note: R uses <- for assignment (though = also works). Python uses = exclusively. R’s basic numeric type is double; Python distinguishes int and float.


2. Vectors / Lists

R

# Atomic vector (all same type)
nums <- c(1, 2, 3, 4, 5)
nums
[1] 1 2 3 4 5
# 1-based indexing
nums[1]       # first element
[1] 1
nums[2:4]     # slice
[1] 2 3 4
# Named vector
scores <- c(math = 95, english = 88, sci = 91)
scores["math"]
math 
  95 

Python

# List (mixed types allowed)
nums = [1, 2, 3, 4, 5]
print(nums)
[1, 2, 3, 4, 5]
# 0-based indexing
print(nums[0])      # first element
1
print(nums[1:4])    # slice
[2, 3, 4]
# Dictionary (like named vector)
scores = {"math": 95, "english": 88, "sci": 91}
print(scores["math"])
95

Note: R vectors are 1-indexed; Python lists are 0-indexed. R vectors must be homogeneous; Python lists can hold mixed types.


3. Control Flow

R

# if / else if / else
temp <- 22

if (temp > 30) {
  cat("Hot\n")
} else if (temp > 20) {
  cat("Warm\n")
} else {
  cat("Cool\n")
}
Warm
# for loop
for (i in 1:5) {
  cat(i, "")
}
1 2 3 4 5 
cat("\n")
# while loop
n <- 1
while (n <= 3) {
  cat(n, "")
  n <- n + 1
}
1 2 3 

Python

# if / elif / else
temp = 22

if temp > 30:
    print("Hot")
elif temp > 20:
    print("Warm")
else:
    print("Cool")
Warm
# for loop
for i in range(1, 6):
    print(i, end=" ")
1 2 3 4 5 
print()
# while loop
n = 1
while n <= 3:
    print(n, end=" ")
    n += 1
1 2 3 

Note: R uses curly braces {} for blocks; Python uses indentation. R’s else if becomes elif in Python.


4. Functions

R

# Define a function
greet <- function(name, greeting = "Hello") {
  paste(greeting, name)
}

greet("Alice")
[1] "Hello Alice"
greet("Bob", greeting = "Hi")
[1] "Hi Bob"
# Anonymous function (lambda)
square <- \(x) x^2
square(5)
[1] 25

Python

# Define a function
def greet(name, greeting="Hello"):
    return f"{greeting} {name}"

print(greet("Alice"))
Hello Alice
print(greet("Bob", greeting="Hi"))
Hi Bob
# Anonymous function (lambda)
square = lambda x: x**2
print(square(5))
25

Note: R functions return the last evaluated expression implicitly. Python requires an explicit return statement.


5. Data Structures: Data Frames

R

# Create a data frame
df <- data.frame(
  name  = c("Alice", "Bob", "Carol"),
  age   = c(25, 30, 28),
  score = c(88.5, 92.0, 79.5)
)

df
   name age score
1 Alice  25  88.5
2   Bob  30  92.0
3 Carol  28  79.5
nrow(df)
[1] 3
df$age          # column access
[1] 25 30 28
df[df$age > 26, ] # filter rows
   name age score
2   Bob  30  92.0
3 Carol  28  79.5

Python

import pandas as pd

# Create a DataFrame
df = pd.DataFrame({
    "name":  ["Alice", "Bob", "Carol"],
    "age":   [25, 30, 28],
    "score": [88.5, 92.0, 79.5]
})

print(df)
    name  age  score
0  Alice   25   88.5
1    Bob   30   92.0
2  Carol   28   79.5
print(len(df))
3
print(df["age"])          # column access
0    25
1    30
2    28
Name: age, dtype: int64
print(df[df["age"] > 26]) # filter rows
    name  age  score
1    Bob   30   92.0
2  Carol   28   79.5

Note: R has a built-in data.frame; Python relies on the pandas library. Column access in R uses $; pandas uses ["col"] or .col.


6. String Operations

R

s <- "Hello, World!"

nchar(s)                      # length
[1] 13
toupper(s)                    # uppercase
[1] "HELLO, WORLD!"
tolower(s)                    # lowercase
[1] "hello, world!"
substring(s, 1, 5)            # slice
[1] "Hello"
gsub("World", "R", s)         # replace
[1] "Hello, R!"
strsplit(s, ", ")[[1]]        # split
[1] "Hello"  "World!"
paste("Hello", "R", sep = " ") # concat
[1] "Hello R"

Python

s = "Hello, World!"

print(len(s))                 # length
13
print(s.upper())              # uppercase
HELLO, WORLD!
print(s.lower())              # lowercase
hello, world!
print(s[0:5])                 # slice
Hello
print(s.replace("World","Python")) # replace
Hello, Python!
print(s.split(", "))          # split
['Hello', 'World!']
print("Hello" + " " + "Python")   # concat
Hello Python

7. Error Handling

R

# tryCatch
result <- tryCatch({
  log(-1)         # returns NaN with a warning
  "success"
}, warning = function(w) {
  paste("Warning caught:", conditionMessage(w))
}, error = function(e) {
  paste("Error caught:", conditionMessage(e))
})

result
[1] "Warning caught: NaNs produced"

Python

import math

# try / except
try:
    result = math.log(-1)
    print("success")
except ValueError as e:
    print(f"Error caught: {e}")
except Exception as e:
    print(f"Unexpected error: {e}")
Error caught: expected a positive input

8. Functional Programming

R

nums <- 1:6

# Map equivalent
squared <- sapply(nums, \(x) x^2)
squared
[1]  1  4  9 16 25 36
# Filter equivalent
evens <- Filter(\(x) x %% 2 == 0, nums)
evens
[1] 2 4 6
# Reduce
total <- Reduce(`+`, nums)
total
[1] 21

Python

from functools import reduce

nums = range(1, 7)

# Map
squared = list(map(lambda x: x**2, nums))
print(squared)
[1, 4, 9, 16, 25, 36]
# Filter
evens = list(filter(lambda x: x % 2 == 0, nums))
print(evens)
[2, 4, 6]
# Reduce
total = reduce(lambda a, b: a + b, nums)
print(total)
21

Summary Table

Feature R Python
Assignment x <- 1 x = 1
Indexing 1-based 0-based
Block syntax Curly braces {} Indentation
Null value NULL / NA None
Data frame Built-in data.frame pandas.DataFrame
Anonymous function \(x) x + 1 lambda x: x + 1
String formatting sprintf() / glue f-strings f"{}"
Package install install.packages("pkg") pip install pkg
Package load library(pkg) import pkg
Implicit return Yes (last expression) No (needs return)
Vectorized ops Native Via NumPy
Error handling tryCatch() try / except

Generated with Quarto. Run with quarto render notebook.qmd.