📘 R Programming - Complete Test Notes
IIT Spoken Tutorial Exam Guide
Target Score: 60-70% Guaranteed ✅
📌 How to Use These Notes:
Focus on topics marked with ⭐⭐⭐⭐ (80% of test questions)
Practice each code example at least once
Memorize common function syntax
Review "Quick Tips" section before the test
1. R vs RStudio ⭐
R RStudio
Programming language (the engine) IDE/Interface (code editor + console + plots)
Does the computation Makes R easier to use
2. Basic Commands ⭐⭐⭐
# Working Directory
getwd() # Get current working directory
setwd('/path/to/folder') # Set working directory
# Help & Documentation
help(mean) or ?mean # Get help for function
demo(graphics) # Run demo
# Console Operations
print('Hello World') # Print to console
q() # Quit R session
# Workspace Management
ls() # List all objects in workspace
rm(x) # Remove object x
rm(list=ls()) # Clear entire workspace
3. Vectors ⭐⭐⭐⭐
Creating Vectors
x <- c(1, 2, 3, 4, 5) # Combine values
y <- seq(1, 10, by=2) # Sequence: 1,3,5,7,9
z <- rep(5, 3) # Repeat: 5,5,5
w <- 1:10 # Shortcut: 1,2,3...10
Indexing Vectors
x[1] # First element (R starts at 1!)
x[2:4] # Elements 2 to 4
x[c(1,3,5)] # Elements 1, 3, and 5
x[-2] # All except 2nd element
Vector Functions
length(x) # Number of elements
sum(x) # Add all elements
mean(x) # Average
median(x) # Middle value
max(x), min(x) # Maximum, minimum
sort(x) # Sort ascending
sort(x, decreasing=TRUE) # Sort descending
Special Values
NA # Missing value
NULL # No value/empty
[Link](x) # Check for NA values
4. Data Frames ⭐⭐⭐⭐
Creating Data Frames
df <- [Link](
name = c('Alice', 'Bob', 'Charlie'),
age = c(20, 25, 30),
score = c(85, 90, 78)
)
Viewing Data
head(df) # First 6 rows
tail(df) # Last 6 rows
View(df) # Open in viewer
str(df) # Structure of data frame
Dimensions
nrow(df) # Number of rows
ncol(df) # Number of columns
dim(df) # Both (rows, cols)
names(df) # Column names
Accessing Data
df$name # Access column 'name'
df[1, ] # First row, all columns
df[ , 2] # All rows, second column
df[1, 2] # Row 1, Column 2
df[1:3, ] # Rows 1 to 3
df[df$age > 22, ] # Filter: age greater than 22
Adding Columns
df$passed <- c(TRUE, TRUE, FALSE) # Add new column
Import/Export
df <- [Link]('[Link]') # Read CSV file
[Link](df, '[Link]') # Write to CSV
5. Plots ⭐⭐⭐
Pie Chart
pie(c(10, 20, 30),
labels = c('A', 'B', 'C'),
main = 'Pie Chart Title',
col = c('red', 'blue', 'green'))
Bar Plot
barplot(c(3, 5, 7, 4),
[Link] = c('Q1', 'Q2', 'Q3', 'Q4'),
main = 'Sales Report',
xlab = 'Quarter',
ylab = 'Sales',
col = 'steelblue')
Histogram
hist(c(12, 15, 18, 20, 22, 25, 28),
main = 'Age Distribution',
xlab = 'Age',
ylab = 'Frequency',
col = 'orange',
breaks = 5) # Number of bins
📊 Common Plot Arguments:
main = Title
xlab = X-axis label
ylab = Y-axis label
col = Color
border = Border color
6. Loops & Conditions ⭐⭐⭐⭐
IF-ELSE
x <- 10
if (x > 5) {
print('Greater than 5')
} else {
print('Less than or equal to 5')
}
IF-ELSE IF
score <- 75
if (score >= 90) {
print('A Grade')
} else if (score >= 75) {
print('B Grade')
} else {
print('C Grade')
}
FOR LOOP
for (i in 1:5) {
print(i)
}
for (name in c('Alice', 'Bob', 'Charlie')) {
print(name)
}
WHILE LOOP
i <- 1
while (i <= 5) {
print(i)
i <- i + 1
}
BREAK & NEXT
# BREAK (exit loop)
for (i in 1:10) {
if (i == 5) break
print(i)
}
# NEXT (skip iteration)
for (i in 1:5) {
if (i == 3) next
print(i)
}
7. Logical Operators ⭐⭐
Comparison Operators
x == y # Equal to
x != y # Not equal
x > y # Greater than
x < y # Less than
x >= y # Greater or equal
x <= y # Less or equal
Logical Operators
& or && # AND
| or || # OR
! # NOT
# Examples
(5 > 3) & (10 < 20) # TRUE (both true)
(5 > 3) | (10 > 20) # TRUE (at least one true)
!(5 > 3) # FALSE (negates TRUE)
8. Functions ⭐⭐
Creating Functions
add_numbers <- function(a, b) {
result <- a + b
return(result)
}
# Calling function
add_numbers(5, 10) # Returns 15
Functions with Default Arguments
greet <- function(name = 'Guest') {
print(paste('Hello', name))
}
greet() # Hello Guest
greet('Alice') # Hello Alice
9. Other Important Commands ⭐
Type Checking
class(x) # Data type of x
[Link](x) # Check if numeric
[Link](x) # Check if character
[Link](x) # Check if logical
Type Conversion
[Link]('123') # Convert to number
[Link](123) # Convert to text
[Link](1) # Convert to TRUE/FALSE
String Operations
paste('Hello', 'World') # Concatenate: "Hello World"
nchar('Hello') # Number of characters: 5
toupper('hello') # HELLO
tolower('HELLO') # hello
Factors
gender <- factor(c('M', 'F', 'M', 'F'))
levels(gender) # Show unique levels
10. Matrix (Bonus) ⭐
# Creating matrix
m <- matrix(1:9, nrow=3, ncol=3)
m <- matrix(1:9, nrow=3, byrow=TRUE) # Fill by row
# Accessing
m[2, 3] # Row 2, Col 3
m[1, ] # First row
m[ , 2] # Second column
# Combining
rbind(m, c(10,11,12)) # Add row
cbind(m, c(10,11,12)) # Add column
⚠️ Common Mistakes to Avoid:
R indexing starts at 1 (not 0!)
Always use <- for assignment in object creation
Function names are case-sensitive: Mean() won't work, use mean()
Always close parentheses: print() not print
Use $ for columns: df$name not [Link]
🎯 Must Know Cold (80% of test):
1. Vector creation & indexing: c(), seq(), rep(), x[1]
2. Data frame accessing: df$col, df[,], df[1,]
3. Plotting: pie(), barplot(), hist() with main/xlab/ylab/col
4. Control structures: if, else, for, while, break, next
5. File operations: [Link]() and [Link]()
📝 Test Day Strategy:
1. Read questions carefully - many are straightforward
2. Skip tough questions, come back later
3. For coding questions: write comments first, then code
4. Test syntax mentally before writing final answer
5. Stay calm - you only need 60-70%, not 100%
You've Got This! 🚀
Practice these commands once and you're ready to ace the test!