1
# Simple Arithmetic Operations in R
a <- 10
b <- 5
# Addition
sum <- a + b
cat("Sum: ", sum, "\n")
# Subtraction
difference <- a - b
cat("Difference: ", difference, "\n")
# Multiplication
product <- a * b
cat("Product: ", product, "\n")
# Division
quotient <- a / b
cat("Quotient: ", quotient, "\n")
# Modulus
remainder <- a %% b
cat("Remainder: ", remainder, "\n")
# Exponentiation
power <- a^b
cat("Power: ", power, "\n")
2
# Simple Grade Program using if-else
score <- 85
# Check grade based on score
if (score >= 90) {
grade <- "A"
} else if (score >= 80) {
grade <- "B"
} else if (score >= 70) {
grade <- "C"
} else if (score >= 60) {
grade <- "D"
} else {
grade <- "F"
}
cat("The grade is:", grade, "\n")
3
add_numbers <- function(a, b) {
return(a + b)
}
# Call the function
result <- add_numbers(3, 4)
cat("Sum is:", result, "\n")
# Recursive function to calculate factorial
factorial <- function(n) {
if (n == 0) {
return(1)
} else {
return(n * factorial(n - 1))
}
}
# Call the recursive function
result <- factorial(4)
cat("Factorial is:", result, "\n")
4
vector
# Create a simple vector
numbers <- c(1, 2, 3, 4, 5)
# Print the vector
cat("The vector is:", numbers, "\n")
# Access an element from the vector (e.g., the 3rd element)
third_element <- numbers[3]
cat("The 3rd element is:", third_element, "\n")
# Add elements to the vector
numbers <- c(numbers, 6, 7)
cat("Updated vector is:", numbers, "\n")
# Sum of all elements in the vector
sum_numbers <- sum(numbers)
cat("Sum of the vector elements is:", sum_numbers, "\n")
list
# Create a simple list
my_list <- list(1, "apple", TRUE)
# Print the list
print(my_list)
# Access the first element of the list
print(my_list[[1]])
# Access the second element of the list
print(my_list[[2]])
matrix
# Create a simple 2x2 matrix
my_matrix <- matrix(c(1, 2, 3, 4), nrow = 2)
# Print the matrix
print("The matrix is:")
print(my_matrix)
# Access an element (1st row, 2nd column)
element <- my_matrix[1, 2]
cat("Element at 1st row, 2nd column:", element, "\n")
# Modify an element (change the element at 2nd row, 1st column)
my_matrix[2, 1] <- 10
cat("Matrix after modification:\n")
print(my_matrix)
array
# Create a simple 3D array (2x2x3)
my_array <- array(1:12, dim = c(2, 2, 3))
# Print the array
cat("The array is:\n")
print(my_array)
# Access an element from the array (1st row, 2nd column, 3rd matrix)
element <- my_array[1, 2, 3]
cat("Element at 1st row, 2nd column, 3rd matrix:", element, "\n")
# Modify an element in the array (change the element at 2nd row, 1st column, 2nd matrix)
my_array[2, 1, 2] <- 99
cat("Array after modification:\n")
print(my_array)
frame
# Create a simple data frame
my_data_frame <- data.frame(
Name = c("Alice", "Bob", "Charlie"),
Age = c(25, 30, 35)
)
# Print the data frame
print(my_data_frame)
# Access a specific column (Age)
age_column <- my_data_frame$Age
print(age_column)
# Access a specific element (2nd row, 1st column)
element <- my_data_frame[2, 1]
print(element)
factor
# Create a simple factor
my_factor <- factor(c("Apple", "Banana", "Apple", "Orange"))
# Print the factor
print(my_factor)
# Print the levels of the factor
print(levels(my_factor))
5
# Install a package (e.g., ggplot2) if not already installed
if (!require(ggplot2)) {
install.packages("ggplot2")
}
# Load the package
library(ggplot2)
# Use the package to create a simple plot
data(mpg) # Built-in dataset in ggplot2
ggplot(mpg, aes(x = displ, y = hwy)) +
geom_point() +
ggtitle("Engine Displacement vs Highway MPG")
6
files
# Create a simple data frame
my_data <- data.frame(
Name = c("Alice", "Bob", "Charlie"),
Age = c(25, 30, 35),
Score = c(90, 85, 88)
)
# Write the data frame to a CSV file
write.csv(my_data, "my_data.csv", row.names = FALSE)
# Read the data back from the CSV file
read_data <- read.csv("my_data.csv")
# Print the read data
cat("Data read from CSV:\n")
print(read_data)
db
# Install and load RSQLite package if it's not installed
if (!require(RSQLite)) {
install.packages("RSQLite")
}
library(RSQLite)
# Create a connection to a new SQLite database
conn <- dbConnect(RSQLite::SQLite(), "my_database.sqlite")
# Create a table in the database
dbExecute(conn, "CREATE TABLE IF NOT EXISTS people (Name TEXT, Age INTEGER, Score
INTEGER)")
# Insert some data into the table
dbExecute(conn, "INSERT INTO people (Name, Age, Score) VALUES ('Alice', 25, 90), ('Bob',
30, 85), ('Charlie', 35, 88)")
# Query the database to get the data
result <- dbGetQuery(conn, "SELECT * FROM people")
# Print the result
cat("Data from SQLite database:\n")
print(result)
# Close the database connection
dbDisconnect(conn)
7
charts
# Create a simple pie chart using base R
slices <- c(25, 35, 40)
labels <- c("Apple", "Banana", "Orange")
# Pie chart
pie(slices, labels = labels, col = c("lightblue", "lightgreen", "lightcoral"), main = "Fruit Pie
Chart")
graph
# Create data
categories <- c("A", "B", "C", "D")
values <- c(12, 9, 15, 7)
# Bar graph
barplot(values, names.arg = categories, col = "lightblue", main = "Bar Graph", xlab =
"Categories", ylab = "Values")
8
# Simple Data
data <- c(12, 15, 18, 20, 20, 25, 30, 35, 35, 40)
# Mean
mean_value <- mean(data)
cat("Mean:", mean_value, "\n")
# Median
median_value <- median(data)
cat("Median:", median_value, "\n")
# Mode function (Custom function, as R doesn't have a built-in mode function)
getmode <- function(v) {
uniqv <- unique(v)
uniqv[which.max(tabulate(match(v, uniqv)))]
}
mode_value <- getmode(data)
cat("Mode:", mode_value, "\n")
# Binomial Distribution Example
n <- 10 # Number of trials
p <- 0.5 # Probability of success
x <- 3 # Number of successes
# Probability of getting exactly 3 successes
prob_exact_3 <- dbinom(x, n, p)
cat("Probability of exactly 3 successes (Binomial):", prob_exact_3, "\n")
# Cumulative probability of getting 3 or fewer successes
prob_up_to_3 <- pbinom(x, n, p)
cat("Cumulative probability of 3 or fewer successes (Binomial):", prob_up_to_3, "\n")
# Normal Distribution Example
mean_norm <- 0 # Mean of the normal distribution
sd_norm <- 1 # Standard deviation of the normal distribution
x_norm <- 1 # Point for which we want to find the probability density
# Probability Density Function (PDF) for the normal distribution at x = 1
pdf_value <- dnorm(x_norm, mean = mean_norm, sd = sd_norm)
cat("PDF value at x = 1 (Normal):", pdf_value, "\n")
# Cumulative Distribution Function (CDF) for the normal distribution at x = 1
cdf_value <- pnorm(x_norm, mean = mean_norm, sd = sd_norm)
cat("CDF value at x = 1 (Normal):", cdf_value, "\n")
# Generate random numbers from a normal distribution
random_numbers <- rnorm(1000, mean = mean_norm, sd = sd_norm)
# Plot the histogram of the random numbers (Normal Distribution)
hist(random_numbers, breaks = 30, col = "lightblue", main = "Histogram of Random Normal
Numbers", xlab = "Value")
9
# Install and load the necessary package
if (!require(forecast)) {
install.packages("forecast")
}
library(forecast)
# Example: Monthly data for 2 years (24 months)
data <- c(120, 125, 130, 135, 140, 145, 150, 160, 170, 180, 190, 200,
210, 215, 220, 225, 230, 240, 250, 260, 270, 280, 290, 300)
# Convert the data into a time series object (monthly data)
ts_data <- ts(data, frequency = 12, start = c(2020, 1))
# Plot the original time series data
plot(ts_data, main = "Original Time Series Data", ylab = "Value", xlab = "Time")
# Fit an ARIMA model automatically
arima_model <- auto.arima(ts_data)
# Forecast the next 12 months (1 year ahead)
forecast_data <- forecast(arima_model, h = 12)
# Plot the forecast
plot(forecast_data, main = "ARIMA Forecast")
10
# Simple Data
categories <- c("Apple", "Banana", "Orange")
values <- c(10, 20, 30)
# Bar Plot
barplot(values, names.arg = categories, col = "lightblue", main = "Fruit Count", xlab = "Fruit",
ylab = "Count")
# Line Plot
x <- 1:10
y <- x^2
plot(x, y, type = "l", col = "blue", lwd = 2, main = "Line Plot of x vs x^2", xlab = "x", ylab =
"x^2")
# Scatter Plot
x <- rnorm(100) # 100 random numbers
y <- rnorm(100)
plot(x, y, main = "Scatter Plot", xlab = "X Values", ylab = "Y Values", pch = 19, col = "red")
# Histogram
data <- rnorm(1000) # 1000 random values from a normal distribution
hist(data, main = "Histogram of Random Data", xlab = "Value", col = "lightgreen", border =
"black", breaks = 30)