# 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"
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.
# 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"
# 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 isdouble; Python distinguishesintandfloat.
# 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
# List (mixed types allowed)
nums = [1, 2, 3, 4, 5]
print(nums)[1, 2, 3, 4, 5]
# 0-based indexing
print(nums[0]) # first element1
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.
# 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
# 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 += 11 2 3
Note: R uses curly braces
{}for blocks; Python uses indentation. R’selse ifbecomeselifin Python.
# 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
# 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
returnstatement.
# 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
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 access0 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.
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"
s = "Hello, World!"
print(len(s)) # length13
print(s.upper()) # uppercaseHELLO, WORLD!
print(s.lower()) # lowercasehello, world!
print(s[0:5]) # sliceHello
print(s.replace("World","Python")) # replaceHello, Python!
print(s.split(", ")) # split['Hello', 'World!']
print("Hello" + " " + "Python") # concatHello Python
# 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"
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
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
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
| 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.