R Program
R Program
a <- 10
b <- 5
# Addition
sum <- a + b
# Subtraction
difference <- a - b
# Multiplication
product <- a * b
# Division
quotient <- a / b
# Modulus
remainder <- a %% b
# Exponentiation
score <- 85
3
add_numbers <- function(a, b) {
return(a + b)
}
# Call the function
result <- add_numbers(3, 4)
cat("Sum 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")
list
# Create a simple list
my_list <- list(1, "apple", TRUE)
matrix
# Create a simple 2x2 matrix
my_matrix <- matrix(c(1, 2, 3, 4), nrow = 2)
# 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)
factor
# Create a simple factor
my_factor <- factor(c("Apple", "Banana", "Apple", "Orange"))
db
# Install and load RSQLite package if it's not installed
if (!require(RSQLite)) {
install.packages("RSQLite")
}
library(RSQLite)
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")
# 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)