Welcome to The Coding College! In this guide, we’ll walk you through a collection of real-world examples in R programming. Whether you’re a beginner or an experienced developer, these examples will help you grasp the core functionality of R in data analysis, visualization, and more.
By exploring these examples, you’ll learn how to:
- Perform common operations in R.
- Handle data structures like vectors, data frames, and matrices.
- Create visualizations like bar plots and scatterplots.
- Solve statistical problems using R.
Let’s dive into the examples!
1. Basic Arithmetic in R
R can perform basic arithmetic operations just like a calculator.
Example
# Perform arithmetic
addition <- 10 + 5
subtraction <- 10 - 5
multiplication <- 10 * 5
division <- 10 / 5
exponentiation <- 2^3
# Print results
print(paste("Addition:", addition))
print(paste("Subtraction:", subtraction))
print(paste("Multiplication:", multiplication))
print(paste("Division:", division))
print(paste("Exponentiation:", exponentiation))
Output:
Addition: 15
Subtraction: 5
Multiplication: 50
Division: 2
Exponentiation: 8
2. Create and Manipulate Vectors
Vectors are one of the most commonly used data structures in R.
Example
# Create a vector
numbers <- c(10, 20, 30, 40, 50)
# Access elements
print(numbers[2]) # Access the second element
# Perform operations
doubled <- numbers * 2
print(doubled) # Multiply each element by 2
Output:
[1] 20
[1] 20 40 60 80 100
3. Working with Data Frames
Data frames are essential for managing tabular data.
Example
# Create a data frame
data <- data.frame(
Name = c("Alice", "Bob", "Charlie"),
Age = c(25, 30, 35),
Score = c(90, 85, 95)
)
# Access a column
print(data$Age)
# Add a new column
data$Passed <- data$Score > 80
# Print the updated data frame
print(data)
Output:
[1] 25 30 35
Name Age Score Passed
1 Alice 25 90 TRUE
2 Bob 30 85 TRUE
3 Charlie 35 95 TRUE
4. Calculate Descriptive Statistics
R makes it easy to calculate mean, median, standard deviation, and more.
Example
# Create a vector of numbers
numbers <- c(10, 20, 30, 40, 50)
# Calculate statistics
mean_value <- mean(numbers)
median_value <- median(numbers)
std_dev <- sd(numbers)
# Print results
print(paste("Mean:", mean_value))
print(paste("Median:", median_value))
print(paste("Standard Deviation:", std_dev))
Output:
Mean: 30
Median: 30
Standard Deviation: 15.811
5. Create a Scatter Plot
R provides powerful plotting tools for data visualization.
Example
# Create data
x <- c(1, 2, 3, 4, 5)
y <- c(10, 20, 30, 40, 50)
# Create a scatter plot
plot(x, y, main = "Scatter Plot Example", xlab = "X-Axis", ylab = "Y-Axis", col = "blue", pch = 16)
This will generate a scatter plot with blue dots.
6. Fit a Linear Model
R is widely used for statistical modeling.
Example
# Create data
x <- c(1, 2, 3, 4, 5)
y <- c(2, 4, 6, 8, 10)
# Fit a linear model
model <- lm(y ~ x)
# Print summary of the model
print(summary(model))
Output: The output will include model coefficients and statistical details.
7. Use Conditional Statements
Conditional statements like if
and else
are used to make decisions in R.
Example
# Check if a number is positive or negative
number <- -10
if (number > 0) {
print("The number is positive")
} else {
print("The number is negative")
}
Output:
The number is negative
8. Loop Through Data
Loops in R allow you to perform repetitive tasks.
Example: For Loop
# Create a vector
numbers <- c(1, 2, 3, 4, 5)
# Loop through each element
for (num in numbers) {
print(num^2) # Print the square of each number
}
Output:
1
4
9
16
25
9. Handle Missing Values
Missing values in R are represented as NA
.
Example
# Create a vector with missing values
numbers <- c(10, 20, NA, 40, 50)
# Remove missing values
cleaned_numbers <- na.omit(numbers)
# Calculate mean of cleaned data
mean_cleaned <- mean(cleaned_numbers)
# Print results
print(paste("Mean (excluding NA):", mean_cleaned))
Output:
Mean (excluding NA): 30
10. Perform String Operations
Strings are important for handling text data in R.
Example
# Create strings
text1 <- "Hello"
text2 <- "World"
# Concatenate strings
greeting <- paste(text1, text2, sep = " ")
# Print the result
print(greeting)
Output:
Hello World
Conclusion
R is a versatile programming language with countless applications in data analysis, statistics, and machine learning. These practical examples are just the beginning of what you can achieve with R.