Advertisement
iykuk

Untitled

Apr 21st, 2024 (edited)
136
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
R 8.70 KB | Source Code | 0 0
  1. // - if else
  2. x<-as.integer(readline(“Enter first number:))
  3. Enter first number:10
  4. y<-as.integer(readline(“Enter second number:))
  5. Enter second number:20
  6. z<-as.integer(readline(“Enter third number:))
  7. Enter third number:30
  8. if (x > y && x > z) {
  9.  print(paste("The greatest number is:", x))
  10.  } else if (y > z) {
  11.  print(paste("The greatest number is:", y))
  12.  } else {
  13.  print(paste("The greatest number is:", z))
  14.  }
  15. // - switch
  16. month <- as.integer(readline(“Enter month number:))
  17. Enter month number:5
  18. season <- switch(month,
  19. "Winter","Spring","Spring","Summer","Summer"," Summer ","Summer",
  20. "Rainy","Rainy","Rainy","Winter","Winter")
  21. print(season)
  22.  
  23. // looping
  24. // for loop
  25. n <- as.integer(readline(“Enter a number:)
  26. Enter a number:5
  27. sum <- 0
  28. for(i in 1:n){
  29.  sum=sum+i
  30. }
  31. print(sum)
  32.  
  33. // while loop
  34. n <- as.integer(readline(“Enter a number:)
  35. Enter a number:6
  36. sum <- 0
  37. i <- 1
  38. while(i<=n){
  39.  sum=sum+i
  40.  i=i+1
  41. }
  42. print(sum)
  43.                
  44. // factorial
  45. num=readline("Enter a Number:")
  46. Enter a Number:10
  47. num=as.integer(num)
  48. factorial=1
  49. if(num<0)
  50.  {
  51.  print("Factorial does not exisit")
  52.  } else if(num==0){
  53.  print("Factorial of 0 is 1")
  54.  } else{
  55.  for(i in 1:num)
  56.  {
  57.  factorial=factorial*i
  58.  }
  59.  print(paste("Factorial of the Given Number:" ,factorial))
  60.  }
  61.  
  62. // factorial
  63. # take input from the user
  64. num = as.integer(readline(prompt="Enter a number: "))
  65. factorial = 1
  66. # check is the number is negative or possitive
  67. if(num < 0) {
  68. print("Not possible for negative numbers")
  69. } else if(num == 0) {
  70. print("The factorial of 0 is 1")
  71. } else {
  72. for(i in 1:num) {
  73.     factorial = factorial * i
  74. }
  75. print(paste("The factorial of", num ,"is",factorial))
  76. }
  77.  
  78. // prime number
  79. isprime <- function(n) {
  80.     lim <- n/2
  81.     prime <- T
  82.     for( i in 2:lim) {
  83.       if(n %% i == 0)
  84.         prime <- FALSE
  85.      
  86.   }
  87.  
  88. if(n==2) prime <- T
  89.     if(prime) print(paste(n," is a Prime Number"))
  90.     else print(paste(n," is a Composite Number"))
  91. }
  92.  
  93. ------------------------------------------------------------
  94. #Implementation of Random Forest using Iris Dataset
  95. ------------------------------------------------------------
  96. library(readxl)
  97. iris<-read_excel("C:/Downloads/iris.xlsx")
  98. #Loadingdata
  99. data(iris)
  100. head(iris)
  101. tail(iris)
  102. #Structure
  103. str(iris)
  104. #Installingpackages
  105. install.packages("caTools")
  106. library(caTools)
  107. install.packages("randomForest")
  108. library(randomForest)
  109. install.packages("caret")
  110. library(caret)
  111. #Splittingdataintotrainingandtestingsets
  112. split<-caTools::sample.split(iris,SplitRatio=0.7)
  113. split
  114. train<-subset(iris,split=="TRUE")
  115. test<-subset(iris,split=="FALSE")
  116. #FittingRandomForesttothetraindataset
  117. control<-trainControl(method="repeatedcv",number=10,repeats=3)
  118. seed<-7
  119. metric<-"Accuracy"
  120. set.seed(seed)
  121. rf<-train(Species~.,data=iris,method="rf",metric=metric,tuneLength=15,
  122. trControl=control)
  123. print(rf)
  124. # Grid Search
  125. tunegrid <- expand.grid(.mtry=c(1:4))
  126. rf_gridsearch <- train(Species~., data=iris, method="rf", metric=metric,
  127.  tuneGrid=tunegrid, trControl=control)
  128. print(rf_gridsearch)
  129. plot(rf_gridsearch)
  130.  
  131. --------------------------------------
  132. // Titanic Survival Prediction using Naive Bayes Algorithm
  133. ---------------------------------------
  134.  
  135. install.packages(c("dplyr", "caret", "e1071", "ggplot2"))
  136. library(dplyr)
  137. library(caret)
  138. library(e1071)
  139. library(ggplot2)
  140.  
  141. titanic <- read.csv("titanic_data.csv") %>%
  142.   select(survived, pclass, sex, sibsp, parch) %>%
  143.   na.omit()
  144.  
  145. titanic$survived <- factor(titanic$survived)
  146. titanic$pclass <- factor(titanic$pclass, levels = c(3, 2, 1))
  147.  
  148. ggplot(titanic, aes(x = survived)) +
  149.   geom_bar(width = 0.5, fill = "coral") +
  150.   geom_text(stat = 'count', aes(label = stat(count)), vjust = -0.5) +
  151.   theme_classic()
  152.  
  153. train_test_split <- function(data, fraction = 0.8, train = TRUE) {
  154.   total_rows <- nrow(data)
  155.   train_rows <- fraction * total_rows
  156.   sample <- sample.int(total_rows, train_rows)
  157.   if (train) {
  158.     return(data[sample, ])
  159.   } else {
  160.     return(data[-sample, ])
  161.   }
  162. }
  163.  
  164. train <- train_test_split(titanic)
  165. test <- train_test_split(titanic, train = FALSE)
  166.  
  167. nb_model <- naiveBayes(survived ~., data = train)
  168. nb_predict <- predict(nb_model, test)
  169. table_mat <- table(nb_predict, test$survived)
  170. table_mat
  171.  
  172. nb_accuracy <- sum(diag(table_mat)) / sum(table_mat)
  173. paste("The accuracy is : ", nb_accuracy)
  174.  
  175.  
  176. ------------------------------------------------------------
  177. #titanic survival
  178. ------------------------------------------------------------
  179. # Load necessary libraries
  180. library(dplyr)
  181. library(e1071)
  182. library(ggplot2)
  183. # Load the Titanic dataset
  184. titanic <- read.csv("C:\\Downloads\\titanic_data.csv")
  185. # Keep only the relevant columns
  186. titanic <- titanic %>%
  187.  select(survived, pclass, sex, sibsp, parch) %>%
  188.  na.omit()
  189. # Convert columns to factors
  190. titanic$survived <- factor(titanic$survived)
  191. titanic$pclass <- factor(titanic$pclass, levels = c(3, 2, 1))
  192. # Plot the survival distribution
  193. ggplot(titanic, aes(x = survived)) +
  194.  geom_bar(width = 0.5, fill = "coral") +
  195.  geom_text(stat = 'count', aes(label = stat(count)), vjust = -0.5) +
  196.  theme_classic()
  197. # Build the Naive Bayes model
  198. nb_model <- e1071::naiveBayes(survived ~ ., data = titanic)
  199. # Make predictions on the test set
  200. nb_predict <- predict(nb_model, titanic)
  201. # Create a confusion matrix
  202. table_mat <- table(nb_predict, titanic$survived)
  203. table_mat
  204. # Calculate accuracy
  205. nb_accuracy <- sum(diag(table_mat)) / sum(table_mat)
  206. paste("The accuracy is:", nb_accuracy)
  207.  
  208. -----------------------
  209. K Means Clustering
  210. -------------------------
  211.  
  212. install.packages("factoextra")
  213. library(factoextra)
  214.  
  215. mydata <- read.csv("D:/R programming/USArrests.csv")
  216.  
  217. USdata <- scale(mydata[, -1])
  218.  
  219. kmeans_results <- lapply(2:5, function(k) {
  220.   kmeans(USdata, centers = k, nstart = 20)
  221. })
  222.  
  223. cluster_assignments <- lapply(kmeans_results, function(result) result$cluster)
  224.  
  225. lapply(kmeans_results, function(result) fviz_cluster(result, data = USdata))
  226.  
  227. fviz_nbclust(USdata, FUN = kmeans, method = "silhouette")
  228.  
  229. ------------------------------------------------------------
  230. #is_prime
  231. ------------------------------------------------------------
  232. function(n) {
  233.  lim <- n/2
  234.  prime <- TRUE
  235.  for(i in 2:lim) {
  236.  if(n %% i == 0) {
  237.  prime <- FALSE
  238.  break
  239.  }
  240.  }
  241.  
  242.  if(n == 2) prime <- TRUE
  243.  if(prime) {
  244.  print(paste(n, " is a Prime Number"))
  245.  } else {
  246.  print(paste(n, " is a Composite Number"))
  247.  }
  248. }
  249. ------------------------------------------------------------
  250. #data_visualization
  251. ------------------------------------------------------------
  252. mydata<-read.csv("C:/Users/hp/Downloads/airquality.csv")
  253. str(mydata)
  254. # Horizontal Bar Plot for Ozone concentration in air
  255. barplot(airquality$Ozone,
  256.  main = 'Ozone Concenteration in air',
  257.  xlab = 'ozone levels', horiz = TRUE)
  258. # Vertical Bar Plot for Ozone concentration in air
  259. barplot(airquality$Ozone, main = 'Ozone Concenteration in air',
  260.  xlab = 'ozone levels', col ='blue', horiz = FALSE)
  261. # Histogram for Maximum Daily Temperature
  262. data(airquality)
  263. hist(airquality$Temp, main ="La Guardia Airport's\
  264. Maximum Temperature(Daily)",
  265.  xlab ="Temperature(Fahrenheit)",
  266.  xlim = c(50, 125), col ="yellow",
  267.  freq = TRUE)
  268. # Box plot for average wind speed
  269. data(airquality)
  270. boxplot(airquality$Wind, main = "Average wind speed\
  271. at La Guardia Airport",
  272.  xlab = "Miles per hour", ylab = "Wind",
  273.  col = "orange", border = "brown",
  274.  horizontal = TRUE, notch = TRUE)
  275. # Multiple Box plots, each representing an Air Quality Parameter
  276. boxplot(airquality[, 0:4],
  277.  main ='Box Plots for Air Quality Parameters')
  278. # Scatter plot for Ozone Concentration per month
  279. data(airquality)
  280. plot(airquality$Ozone, airquality$Month,
  281.  main ="Scatterplot Example",
  282.  xlab ="Ozone Concentration in parts per billion",
  283.  ylab =" Month of observation ", pch = 19)
  284. # Set seed for reproducibility
  285. # set.seed(110)
  286. # Create example data
  287. data <- matrix(rnorm(50, 0, 5), nrow = 5, ncol = 5)
  288. # Column names
  289. colnames(data) <- paste0("col", 1:5)
  290. rownames(data) <- paste0("row", 1:5)
  291. # Draw a heatmap
  292. heatmap(data)
  293. #3D Graphs in R
  294. # Adding Titles and Labeling Axes to Plot
  295. cone <- function(x, y){
  296.  sqrt(x ^ 2 + y ^ 2)
  297. }
  298. # prepare variables.
  299. x <- y <- seq(-1, 1, length = 30)
  300. z <- outer(x, y, cone)
  301. # plot the 3D surface
  302. # Adding Titles and Labeling Axes to Plot
  303. persp(x, y, z,
  304.  main="Perspective Plot of a Cone",
  305.  zlab = "Height",
  306.  theta = 30, phi = 15,
  307.  col = "orange", shade = 0.4)
  308. ---------------------------------------
  309. control and looping statements
  310. ----------------------------------------
  311. for (i in 1:5) {
  312.  print(i)
  313. }
  314. i <- 1
  315. while (i <= 5) {
  316.  print(i)
  317.  i <- i + 1
  318. }
  319. x <- 10
  320. if (x > 5) {
  321.  print("x is greater than 5")
  322. }
  323. x <- 5
  324. if (x < 0) {
  325.  print("x is negative")
  326. } else if (x == 0) {
  327.  print("x is zero")
  328. } else {
  329.  print("x is positive")
  330. }
  331.  
  332.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement