def program():
    print("""
    DSL
    1. vector
    2. list
    3. dataframe
    4. matrix
    5. controlstructure
    6. csvexcelxml
    7. predictive
    8. descriptive
    9. associationrule
    10. barplot
    11. histogrambarpie
""")

def vector():
    print("""
# sum_mean_product
vec <- c(2, 4, 6, 8, 10)
sum_vec <- sum(vec)
mean_vec <- mean(vec)
prod_vec <- prod(vec)
cat("Vector elements: ", vec, "\n")
cat("Sum of vector elements: ", sum_vec, "\n")
cat("Mean of vector elements: ", mean_vec, "\n")
cat("Product of vector elements: ", prod_vec, "\n")

# ascendingdescending 
x = c(10, 20, 30, 25, 9, 26)
print(x)
print(sort(x))
print(sort(x, decreasing=TRUE))

# additionsubstraction
# 2(c). Create two vectors of different lengths,
# convert them to matrices and perform addition & subtraction
vector1 <- c(1, 2, 3, 4, 5)
vector2 <- c(6, 7, 8)
# Convert vectors to matrices
matrix1 <- matrix(vector1, nrow = 5, ncol = 1, byrow = TRUE)
matrix2 <- matrix(vector2, nrow = 3, ncol = 1, byrow = TRUE)
cat("\nMatrix 1 (from vector1):\n")
print(matrix1)
cat("\nMatrix 2 (from vector2):\n")
print(matrix2)
# Reshape matrix2 to match matrix1 dimensions
matrix2_reshaped <- matrix(rep(vector2, length.out = length(vector1)), nrow = 5, ncol = 1)
cat("\nReshaped Matrix 2 to match Matrix 1 dimensions:\n")
print(matrix2_reshaped)
# Addition
addition_result <- matrix1 + matrix2_reshaped
cat("\nAddition of Matrices:\n")
print(addition_result)
# Subtraction
subtraction_result <- matrix1 - matrix2_reshaped
cat("\nSubtraction of Matrices:\n")
print(subtraction_result)

# englishletter
letters_lower <- letters # builtin: 'a' to 'z'
first10_lower <- letters_lower[1:10]
letters_upper <- LETTERS
last10_upper <- letters_upper[(length(letters_upper)-9):length(letters_upper)]
# extract letters 22 to 24 and convert to upper
letters_22_24_upper <- toupper(letters_lower[22:24])
cat("First 10 lowercase:", first10_lower, "\n")
cat("Last 10 uppercase:", last10_upper, "\n")
cat("Letters 22-24 in uppercase:", letters_22_24_upper, "\n")
""")
    

def list():
    print("""
# 3(a). Write an R program to sort a list of 10 strings in ascending and descending order
strs <- as.list(c("Delhi","Mumbai","Pune","Kolkata","Chennai","Bengaluru","Hyderabad","Jaipur","Surat","Lucknow"))
# Sorting: convert to vector, sort, then back to list (if needed)
asc <- as.list(sort(unlist(strs), decreasing = FALSE))
desc <- as.list(sort(unlist(strs), decreasing = TRUE))
cat("Ascending list:\n")
print(asc)
cat("Descending list:\n")
print(desc)

# 3(b). Create a list of cities and perform operations: name elements, add, remove last, update 3rd 
cities <- list("Pune", "Mumbai", "Nashik")
names(cities) <- c("C1","C2","C3")
# Add an element at the end
cities[[length(cities) + 1]] <- "Nagpur"
# Remove last element
cities <- cities[-length(cities)]
# Update 3rd element (if exists)
if(length(cities) >= 3) cities[[3]] <- "Aurangabad"
print(cities)

# 3(c). Create a list of elements using a vector, a matrix and a function. Print contents
v <- c(1,2,3)
m <- matrix(1:6, nrow=2)
f <- function(x) x^2
mylist <- list(numbers = v, mat = m, square = f)
print(mylist)
# call function inside list
cat("Square of 4 via list function:", mylist$square(4), "\n")


# 3(d). Convert a given matrix to a list and print list in ascending order
m <- matrix(c(3,1,4,2,5,6), nrow = 3)
# convert matrix to list of column-vectors
lst_cols <- as.list(as.data.frame(m))
print(lst_cols)
# to sort entire flattened values ascending
sorted_vals <- sort(as.vector(m))
cat("Sorted values from matrix:", sorted_vals, "\n")
""")
    
def dataframe():
    print("""
# 4(a). Create a data frame using two given vectors and display duplicated elements and unique rows
v1 <- c(1,2,2,3,4)
v2 <- c("A","B","B","C","D")
df <- data.frame(id = v1, grp = v2, stringsAsFactors = FALSE)
cat("Data Frame:\n")
print(df)
# duplicated rows
dup_rows <- df[duplicated(df) | duplicated(df, fromLast = TRUE), ]
cat("Duplicated rows:\n")
print(dup_rows)
# unique rows
unique_rows <- unique(df)
cat("Unique rows:\n")
print(unique_rows)

# 4(b) Create a data frame with details of 5 employees and display details in ascending order
emps <- data.frame(
  emp_id = 101:105,
  name = c("Amit","Bina","Chirag","Deepa","Esha"),
  salary = c(50000, 45000, 60000, 52000, 48000),
  stringsAsFactors = FALSE
)
# display in ascending order by name
emps_sorted <- emps[order(emps$name), ]
print(emps_sorted)

# 4(c) Compare two data frames to find elements in first not present in second
df1 <- data.frame(id = 1:5, val = letters[1:5])
df2 <- data.frame(id = c(2,4), val = c('b','d'))
# rows in df1 not in df2 (by all columns)
not_in_df2 <- df1[!apply(df1, 1, function(r) any(apply(df2,1, function(r2) all(r==r2)))), ]
cat("Rows in df1 not present in df2:\n")
print(not_in_df2)

# 4(d) Extract 3rd and 5th rows with 1st and 3rd columns from a given data frame
df <- data.frame(A=1:6, B=letters[1:6], C = rnorm(6))
extracted <- df[c(3,5), c(1,3)]
print(extracted)
""")
    
def matrix():
    print("""
# 5(a) Create a matrix taking a given vector as input and define column and row names. Display the matrix
vec <- 1:12
m <- matrix(vec, nrow = 3, ncol = 4, byrow = TRUE)
rownames(m) <- c('R1','R2','R3')
colnames(m) <- c('C1','C2','C3','C4')
print(m)

# 5(b) Create two 2x3 matrices and add, subtract, multiply and divide the matrices
A <- matrix(c(1,2,3,4,5,6), nrow = 2, byrow = TRUE)
B <- matrix(c(6,5,4,3,2,1), nrow = 2, byrow = TRUE)
addAB <- A + B
subAB <- A - B
# element-wise multiplication and division
mulAB <- A * B
divAB <- A / B
cat("A:\n"); print(A)
cat("B:\n"); print(B)
cat("A+B:\n"); print(addAB)
cat("A-B:\n"); print(subAB)
cat("A*B (element-wise):\n"); print(mulAB)
cat("A/B (element-wise):\n"); print(divAB)

# 5(c) Create a matrix from a list of given vectors
v1 <- c(1,2,3)
v2 <- c(4,5,6)
mat_from_list <- do.call(cbind, list(v1, v2))
print(mat_from_list)

# 5(d) Convert a given matrix to a list of column-vectors
m <- matrix(1:9, nrow=3)
list_cols <- as.list(as.data.frame(m))
print(list_cols)
""")
    
def controlstructure():
    print("""
# 6.1 Fibonacci series
fib <- function(n){
  if(n<=0) return(NULL)
  if(n==1) return(0)
  if(n==2) return(c(0,1))
  a <- 0; b <- 1; res <- c(a,b)
  for(i in 3:n){
    c <- a + b
    res <- c(res, c)
    a <- b; b <- c
  }
  res
}
print(fib(10))

# 6.2 Multiplication table of a given number
mult_table <- function(n, upto=10){
  for(i in 1:upto) cat(n, "x", i, "=", n*i, "\n")
}
mult_table(7, 12)

# 6.3 Armstrong check (for 3-digit numbers generic) (narcissistic) check for a given number
is_armstrong <- function(n){
  digits <- as.integer(unlist(strsplit(as.character(n), split="")))
  sum_pow <- sum(digits ^ length(digits))
  return(sum_pow == n)
}
cat("153 is Armstrong?", is_armstrong(153), "\n")
cat("9474 is Armstrong?", is_armstrong(9474), "\n")
 
# 6.4 Factorial of a number
fact <- function(n){
  if(n==0) return(1)
  res <- 1
  for(i in 1:n) res <- res * i
  res
}
cat("5! =", fact(5), "\n")

# 6.5 Sum of natural numbers up to n
sum_natural <- function(n){
  sum(1:n)
}
cat("Sum 1..10 =", sum_natural(10), "\n")


""")
    
def csvexcelxml():
    print("""
# 7. Reading files: CSV, Excel, XML
# CSV
df_csv <- read.csv('D:/R Program/item.csv', stringsAsFactors = FALSE)
print(df_csv)

# Excel (requires readxl)
install.packages('readxl')
library(readxl)
df_xls <- read_excel('D:/R Program/item.xlsx', sheet = 1)
print(df_xls)

# XML (requires XML package)
install.packages('XML')
library(XML)
xml_doc <- xmlParse('D:/R Program/item.xml')
xml_data <- xmlToDataFrame(nodes = getNodeSet(xml_doc, "//record"))
print(xml_data)

item.csv                  
ID	Name	Age	City
1	John	25	New York
2	Maria	30	Los Angeles
3	Raj	28	Mumbai
4	Sara	22	London
5	Chen	27	Beijing

item.xlsx
ID	Name	Age	City
1	John	25	New York
2	Maria	30	Los Angeles
3	Raj	28	Mumbai
4	Sara	22	London
5	Chen	27	Beijing

item.xml
<?xml version="1.0" encoding="UTF-8"?>
<records>
  <record>
    <ID>1</ID>
    <Name>John</Name>
    <Age>25</Age>
    <City>New York</City>
  </record>
  <record>
    <ID>2</ID>
    <Name>Maria</Name>
    <Age>30</Age>
    <City>Los Angeles</City>
  </record>
  <record>
    <ID>3</ID>
    <Name>Raj</Name>
    <Age>28</Age>
    <City>Mumbai</City>
  </record>
  <record>
    <ID>4</ID>
    <Name>Sara</Name>
    <Age>22</Age>
    <City>London</City>
  </record>
  <record>
    <ID>5</ID>
    <Name>Chen</Name>
    <Age>27</Age>
    <City>Beijing</City>
  </record>
</records>
""")
    
def predictive():
    print("""
# ------------------------------------------------------------
# Program: Predictive Modelling Techniques in R
# Techniques: Linear Regression and Logistic Regression
# ------------------------------------------------------------

# -------------------------------
# 1. Linear Regression
# -------------------------------
cat("\n--- Linear Regression Model ---\n")

# Create sample data
height <- c(150, 155, 160, 165, 170, 175, 180, 185, 190, 195)
weight <- c(50, 52, 54, 57, 60, 62, 65, 67, 70, 72)

# Build linear model
linear_model <- lm(weight ~ height)

# Display model summary
summary(linear_model)

# Predict weight for new height values
new_height <- data.frame(height = c(160, 175, 190))
predicted_weight <- predict(linear_model, new_height)

cat("\nPredicted Weights for Given Heights:\n")
print(predicted_weight)

# Plot
plot(height, weight, main = "Linear Regression: Height vs Weight",
     xlab = "Height (cm)", ylab = "Weight (kg)", col = "blue", pch = 19)
abline(linear_model, col = "red", lwd = 2)


# -------------------------------
# 2. Logistic Regression
# -------------------------------
cat("\n--- Logistic Regression Model ---\n")

# Create sample data
study_hours <- c(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
pass_exam <- c(0, 0, 0, 0, 1, 1, 1, 1, 1, 1)  # 0 = Fail, 1 = Pass

# Build logistic regression model
logistic_model <- glm(pass_exam ~ study_hours, family = binomial)

# Display model summary
summary(logistic_model)

# Predict probability of passing for given hours of study
new_data <- data.frame(study_hours = c(2, 5, 8))
predicted_prob <- predict(logistic_model, new_data, type = "response")

cat("\nPredicted Probability of Passing:\n")
print(predicted_prob)

# Plot logistic curve
plot(study_hours, pass_exam,
     main = "Logistic Regression: Study Hours vs Pass Probability",
     xlab = "Study Hours",
     ylab = "Probability of Passing",
     col = "blue", pch = 19)
curve(predict(logistic_model, data.frame(study_hours = x),
              type = "response"), add = TRUE, col = "red", lwd = 2)

""")
    
def descriptive():
    print("""
# 9(a) K-Means Clustering
# Load the built-in 'iris' dataset
data(iris)
# Select numeric columns only
iris_data <- iris[, 1:4]
# Set seed for reproducibility
set.seed(42)
# Apply K-Means algorithm with 3 clusters
kmeans_result <- kmeans(iris_data, centers = 3)
# Display clustering result
cat("Cluster centers:\n")
print(kmeans_result$centers)
cat("\nCluster assignment of first 10 records:\n")
print(kmeans_result$cluster[1:10])
# Compare actual vs predicted clusters
table(kmeans_result$cluster, iris$Species)
# Visualize clusters
plot(iris_data[, c("Sepal.Length", "Sepal.Width")],
     col = kmeans_result$cluster,
     main = "K-Means Clustering (Iris Data)",
     xlab = "Sepal Length", ylab = "Sepal Width",
     pch = 19)
          
# 9(b) Principal Component Analysis (PCA)
data(iris)
# Use numeric columns only
iris_data <- iris[, 1:4]
# Apply PCA with scaling
pca_result <- prcomp(iris_data, scale. = TRUE)
# Display summary
cat("Summary of PCA:\n")
summary(pca_result)
# Display principal component scores
cat("\nFirst few PCA scores:\n")
head(pca_result$x)
# Biplot visualization
biplot(pca_result, main = "PCA Biplot for Iris Dataset")
""")
    
def associationrule():
    print("""
# Install and load required packages
install.packages("arules")
library(arules)
# -------------------------------------------
# Step 1: Create a sample transaction dataset
# -------------------------------------------
transactions <- list(
  c("Milk", "Bread", "Eggs"),
  c("Milk", "Bread"),
  c("Milk", "Eggs"),
  c("Bread", "Butter"),
  c("Milk", "Bread", "Butter", "Eggs"),
  c("Bread", "Butter"),
  c("Milk", "Eggs")
)
# Convert to transaction format
txn_data <- as(transactions, "transactions")
# View the transaction summary
summary(txn_data)
inspect(txn_data)

# -------------------------------------------
# 1️⃣ Technique 1: Apriori Algorithm
# -------------------------------------------
cat("\n--- Apriori Algorithm Results ---\n")
rules_apriori <- apriori(txn_data, parameter = list(support = 0.3, confidence = 0.7, minlen = 2))
# Display generated rules
inspect(rules_apriori)
# Sort rules by lift
sorted_rules_apriori <- sort(rules_apriori, by = "lift", decreasing = TRUE)
inspect(sorted_rules_apriori[1:5])

# -------------------------------------------
# 2️⃣ Technique 2: Eclat Algorithm
# -------------------------------------------
cat("\n--- Eclat Algorithm Results ---\n")
# Use Eclat to find frequent itemsets
freq_items_eclat <- eclat(txn_data,parameter = list(support = 0.3, minlen = 2))
# Display frequent itemsets
inspect(freq_items_eclat)
# Generate association rules from frequent itemsets (manually)
rules_eclat <- ruleInduction(freq_items_eclat, txn_data, confidence = 0.7)
inspect(rules_eclat)

# -------------------------------------------
# Step 3: Visualization (optional)
# -------------------------------------------
install.packages("arulesViz")
library(arulesViz)
# Plot the Apriori rules
plot(rules_apriori, method = "graph", control = list(type = "items"))

""")
 
def barplot():
    print("""
# Program: Simple Bar Plot of Marks of Five Subjects

# Create data
subjects <- c("Math", "Science", "English", "History", "Computer")
marks <- c(85, 90, 78, 88, 92)

# Create a bar plot
barplot(marks,
        names.arg = subjects,
        col = rainbow(length(subjects)),   # colorful bars
        main = "Marks of Five Subjects",
        xlab = "Subjects",
        ylab = "Marks Obtained",
        border = "black")

# Add numerical labels above bars
text(x = seq_along(marks),
     y = marks,
     labels = marks,
     pos = 3,
     cex = 0.8,
     col = "blue")

""")
    
def histogrambarpie():
    print("""
# Program: Plot Histogram, Bar Chart, and Pie Chart on Sample Data

# -------------------------------
# Sample Data
# -------------------------------
marks <- c(56, 78, 45, 90, 82, 67, 89, 73, 55, 69)

# -------------------------------
# 1. Histogram
# -------------------------------
hist(marks,
     main = "Histogram of Marks",
     xlab = "Marks",
     ylab = "Frequency",
     col = "lightblue",
     border = "black")

# -------------------------------
# 2. Bar Chart
# -------------------------------
subjects <- c("Math", "Science", "English", "History", "Computer")
scores <- c(85, 90, 78, 88, 92)

barplot(scores,
        names.arg = subjects,
        col = rainbow(length(subjects)),
        main = "Bar Chart of Subject Scores",
        xlab = "Subjects",
        ylab = "Scores",
        border = "black")
# -------------------------------
# 3. Pie Chart
# -------------------------------
pie_data <- c(25, 15, 30, 10, 20)
labels <- c("Apples", "Bananas", "Grapes", "Oranges", "Mangoes")

pie(pie_data,
    labels = labels,
    col = rainbow(length(pie_data)),
    main = "Pie Chart of Fruit Distribution")
""")  


