Surya_from_1627

DATA SCIENCE WITH R LAB

Aug 1st, 2026
95
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
R 14.83 KB | None | 0 0
  1. # 1. Compute Mean, Median, Mode, Variance, and Standard Deviation
  2. df <- data.frame(
  3.   EMPID = c(101, 102, 103, 104, 105,
  4.             106, 107, 108, 109, 110),
  5.   EMPNAME = c("Alice", "Bob", "Charlie", "David", "Eva",
  6.               "Frank", "Grace", "Hannah", "Ian", "Julia"),
  7.   SALARY = c(50000, 60000, 55000, 70000, 65000,
  8.              48000, 72000, 58000, 69000, 75000),
  9.   STARTDATE = as.Date(c("2020-01-15", "2019-03-10",
  10.                         "2021-06-25", "2018-07-01",
  11.                         "2020-09-12", "2021-11-05",
  12.                         "2017-04-20", "2022-02-14",
  13.                         "2019-12-30", "2016-05-18"))
  14. )
  15.  
  16. # Mean
  17. mean_salary <- mean(df$SALARY)
  18.  
  19. # Median
  20. median_salary <- median(df$SALARY)
  21.  
  22. # Mode function (R doesn't have built-in mode for stats)
  23. getmode <- function(v) {
  24.   uniqv <- unique(v)
  25.   uniqv[which.max(tabulate(match(v, uniqv)))]
  26. }
  27. mode_salary <- getmode(df$SALARY)
  28.  
  29. # Variance
  30. var_salary <- var(df$SALARY)
  31.  
  32. # Standard Deviation
  33. sd_salary <- sd(df$SALARY)
  34.  
  35. # Print all measures
  36. cat("Mean Salary:", mean_salary, "\n")
  37. cat("Median Salary:", median_salary, "\n")
  38. cat("Mode Salary:", mode_salary, "\n")
  39. cat("Variance Salary:", var_salary, "\n")
  40. cat("SD Salary:", sd_salary, "\n")
  41.  
  42.  
  43. # 2. Visualize Binomial, Normal, and Poisson Distributions
  44. library(dplyr)
  45. library(ggplot2)
  46.  
  47. df <- data.frame(
  48.   Experience = c(1,2,3,4,5,6,7,8,9,10),
  49.   SALARY = c(25000,30000,35000,42000,48000,
  50.              52000,58000,65000,72000,80000)
  51. )
  52.  
  53. # Prepare a tidy data frame for the distributions
  54. mean_salary <- mean(df$SALARY)
  55. sd_salary <- sd(df$SALARY)
  56.  
  57. n_trials <- 20
  58. p_success <- mean(df$SALARY > 60000)
  59.  
  60. binom_df <- tibble::tibble(
  61.   x = 0:n_trials,
  62.   prob = dbinom(0:n_trials, size = n_trials, prob = p_success)
  63. )
  64.  
  65. norm_df <- tibble::tibble(
  66.   x = seq(min(df$SALARY) - 5000, max(df$SALARY) + 5000, length.out = 500),
  67.   density = dnorm(x, mean = mean_salary, sd = sd_salary)
  68. )
  69.  
  70. lambda_pois <- mean(df$SALARY / 1000)
  71. pois_df <- tibble::tibble(
  72.   x = 0:ceiling(lambda_pois + 10),
  73.   prob = dpois(0:ceiling(lambda_pois + 10), lambda = lambda_pois)
  74. )
  75.  
  76. # Binomial plot
  77. ggplot(binom_df, aes(x = x, y = prob)) +
  78.   geom_col(fill = "skyblue", color = "black") +
  79.   labs(title = "Binomial Distribution",
  80.        x = "Number of Successes",
  81.        y = "Probability") +
  82.   theme_minimal()
  83.  
  84. # Normal plot
  85. ggplot(norm_df, aes(x = x, y = density)) +
  86.   geom_line(color = "darkgreen", linewidth = 1.2) +
  87.   geom_vline(xintercept = mean_salary, color = "red", linetype = "dashed") +
  88.   labs(title = "Normal Distribution",
  89.        x = "Salary",
  90.        y = "Density") +
  91.   theme_minimal()
  92.  
  93. # Poisson plot
  94. ggplot(pois_df, aes(x = x, y = prob)) +
  95.   geom_col(fill = "orange", color = "black") +
  96.   labs(title = "Poisson Distribution",
  97.        x = "Count",
  98.        y = "Probability") +
  99.   theme_minimal()
  100.  
  101.  
  102. # 3. Perform t-test and Chi-Square Test in R
  103. # Load the employee data from 1.R
  104. source("1.R")
  105.  
  106. # 1. T-test: test whether the average salary differs from 60,000
  107. salary_t_test <- t.test(df$SALARY, mu = 60000)
  108.  
  109. # 2. Create categories for a chi-square test
  110. # Salary category: High (>= 60,000) or Low (< 60,000)
  111. df$salary_group <- ifelse(df$SALARY >= 60000, "High", "Low")
  112.  
  113. # Experience category: Experienced if joined before 2020, otherwise New
  114. # (using the STARTDATE column from the data frame)
  115. df$experience_group <- ifelse(df$STARTDATE <= as.Date("2019-12-31"), "Experienced", "New")
  116.  
  117. # Contingency table
  118. chi_table <- table(df$salary_group, df$experience_group)
  119.  
  120. # 3. Chi-square test of independence
  121. chi_square_test <- chisq.test(chi_table)
  122.  
  123. # Print results
  124. cat("=== T-test ===\n")
  125. print(salary_t_test)
  126.  
  127. cat("\n=== Contingency Table ===\n")
  128. print(chi_table)
  129.  
  130. cat("\n=== Chi-Square Test ===\n")
  131. print(chi_square_test)
  132.  
  133.  
  134. # 4. Calculate Correlation and Build a Simple Linear Regression Model
  135. df <- data.frame(
  136.   Experience = c(1,2,3,4,5,6,7,8,9,10),
  137.   Salary = c(25000,30000,35000,42000,48000,
  138.              52000,58000,65000,72000,80000)
  139. )
  140.  
  141. print(df)
  142.  
  143. correlation <- cor(df$Experience,
  144.                    df$Salary)
  145.  
  146. cat("Correlation =", correlation, "\n")
  147.  
  148. plot(df$Experience,
  149.      df$Salary,
  150.      main="Experience vs Salary",
  151.      xlab="Experience",
  152.      ylab="Salary",
  153.      pch=19,
  154.      col="blue")
  155.  
  156. model <- lm(Salary ~ Experience,
  157.             data=df)
  158.  
  159. summary(model)
  160.  
  161. coef(model)
  162.  
  163. newdata <- data.frame(
  164.   Experience=12
  165. )
  166.  
  167. predict(model,
  168.         newdata)
  169.  
  170. abline(model,
  171.        col="red",
  172.        lwd=2)
  173.  
  174.  
  175. # 5. Conduct Exploratory Data Analysis (EDA) on a Real-World Dataset
  176. data(mtcars)
  177.  
  178. head(mtcars)
  179.  
  180. str(mtcars)
  181.  
  182. dim(mtcars)
  183.  
  184. names(mtcars)
  185.  
  186. summary(mtcars)
  187.  
  188. colSums(is.na(mtcars))
  189.  
  190. sum(duplicated(mtcars))
  191.  
  192. cor(mtcars)
  193.  
  194. hist(mtcars$mpg,
  195.      main="Histogram of MPG",
  196.      xlab="Miles Per Gallon",
  197.      col="lightblue")
  198.  
  199. boxplot(mtcars$hp,
  200.         main="Horsepower",
  201.         col="orange")
  202.  
  203. plot(mtcars$wt,
  204.      mtcars$mpg,
  205.      main="Weight vs MPG",
  206.      xlab="Weight",
  207.      ylab="MPG",
  208.      pch=19,
  209.      col="blue")
  210.  
  211.  
  212. # 6. Apply Feature Engineering: Scaling, Normalization, and Encoding
  213. df <- data.frame(
  214.   Name = c("Alice","Bob","Charlie","David","Eva"),
  215.   Age = c(23,28,35,40,30),
  216.   Salary = c(30000,45000,60000,80000,55000),
  217.   Gender = c("Female","Male","Male","Male","Female")
  218. )
  219.  
  220. print(df)
  221.  
  222. # Scaling
  223. scaled_data <- scale(df[,c("Age","Salary")])
  224.  
  225. print(scaled_data)
  226.  
  227. # Normalization
  228. normalize <- function(x){
  229.   (x-min(x))/(max(x)-min(x))
  230. }
  231.  
  232. normalized_salary <- normalize(df$Salary)
  233.  
  234. print(normalized_salary)
  235.  
  236. # Encoding
  237. df$Gender_Encoded <- ifelse(df$Gender=="Male",1,0)
  238.  
  239. # Add engineered features
  240. df$Age_Scaled <- scaled_data[,1]
  241. df$Salary_Scaled <- scaled_data[,2]
  242. df$Salary_Normalized <- normalized_salary
  243.  
  244. print(df)
  245.  
  246.  
  247. # 7. Practice R Programming: Variables, Control Structures, and Functions
  248. # Variables
  249. num1 <- 20
  250. num2 <- 10
  251. name <- "Alice"
  252.  
  253. cat("Name:", name, "\n")
  254. cat("Number 1:", num1, "\n")
  255. cat("Number 2:", num2, "\n\n")
  256.  
  257. # Arithmetic Operators
  258. cat("Addition:", num1 + num2, "\n")
  259. cat("Subtraction:", num1 - num2, "\n")
  260. cat("Multiplication:", num1 * num2, "\n")
  261. cat("Division:", num1 / num2, "\n")
  262. cat("Modulus:", num1 %% num2, "\n")
  263. cat("Power:", num1 ^ 2, "\n\n")
  264.  
  265. # Relational Operators
  266. cat("num1 > num2 :", num1 > num2, "\n")
  267. cat("num1 == num2 :", num1 == num2, "\n\n")
  268.  
  269. # If...Else Statement
  270. if(num1 > num2){
  271.   cat("num1 is greater than num2\n\n")
  272. }else{
  273.   cat("num2 is greater than or equal to num1\n\n")
  274. }
  275.  
  276. # For Loop
  277. cat("For Loop:\n")
  278. for(i in 1:5){
  279.   cat(i, "\n")
  280. }
  281.  
  282. cat("\n")
  283.  
  284. # While Loop
  285. cat("While Loop:\n")
  286. count <- 1
  287.  
  288. while(count <= 5){
  289.   cat(count, "\n")
  290.   count <- count + 1
  291. }
  292.  
  293. cat("\n")
  294.  
  295. # User-defined Function
  296. square <- function(x){
  297.   return(x * x)
  298. }
  299.  
  300. result <- square(8)
  301.  
  302. cat("Square of 8 =", result)
  303.  
  304.  
  305. # 8. Read and Write Data from CSV, Excel, JSON, and XML Files
  306. library(readxl)
  307. library(writexl)
  308. library(jsonlite)
  309. library(XML)
  310.  
  311. df <- data.frame(
  312.   ID = c(101,102,103,104),
  313.   Name = c("Alice","Bob","Charlie","David"),
  314.   Age = c(22,24,23,25),
  315.   Salary = c(35000,42000,39000,45000)
  316. )
  317.  
  318. print(df)
  319.  
  320. # CSV
  321. write.csv(df, "employees.csv", row.names = FALSE)
  322.  
  323. csv_data <- read.csv("employees.csv")
  324. print(csv_data)
  325.  
  326. # Excel
  327. write_xlsx(df, "employees.xlsx")
  328.  
  329. excel_data <- read_excel("employees.xlsx")
  330. print(excel_data)
  331.  
  332. # JSON
  333. write_json(df, "employees.json", pretty = TRUE)
  334.  
  335. json_data <- read_json("employees.json")
  336. print(json_data)
  337.  
  338. # XML
  339. xml_data <- newXMLDoc()
  340.  
  341. root <- newXMLNode("Employees", doc = xml_data)
  342.  
  343. for(i in 1:nrow(df))
  344. {
  345.   emp <- newXMLNode("Employee", parent = root)
  346.  
  347.   newXMLNode("ID", df$ID[i], parent = emp)
  348.   newXMLNode("Name", df$Name[i], parent = emp)
  349.   newXMLNode("Age", df$Age[i], parent = emp)
  350.   newXMLNode("Salary", df$Salary[i], parent = emp)
  351. }
  352.  
  353. saveXML(xml_data, file = "employees.xml")
  354.  
  355. xml_file <- xmlParse("employees.xml")
  356.  
  357. print(xmlRoot(xml_file))
  358.  
  359.  
  360. # 9. Use dplyr and tidyr for Data Wrangling Tasks
  361. library(dplyr)
  362. library(tidyr)
  363.  
  364. df <- data.frame(
  365.   ID = c(101,102,103,104,105),
  366.   Name = c("Alice","Bob","Charlie","David","Eva"),
  367.   Department = c("HR","IT","IT","Sales","HR"),
  368.   Salary = c(35000,50000,48000,45000,40000),
  369.   Age = c(25,28,30,27,24)
  370. )
  371.  
  372. print(df)
  373.  
  374. # Select columns
  375. select(df, Name, Salary)
  376.  
  377. # Filter rows
  378. filter(df, Salary > 40000)
  379.  
  380. # Arrange rows
  381. arrange(df, desc(Salary))
  382.  
  383. # Create a new column
  384. df2 <- mutate(df, NewSalary = Salary * 1.10)
  385. print(df2)
  386.  
  387. # Group and summarize
  388. group_by(df, Department) %>%
  389.   summarise(AverageSalary = mean(Salary))
  390.  
  391. # Convert wide to long
  392. long_df <- pivot_longer(
  393.   df,
  394.   cols = c(Salary, Age),
  395.   names_to = "Attribute",
  396.   values_to = "Value"
  397. )
  398.  
  399. print(long_df)
  400.  
  401. # Convert long to wide
  402. wide_df <- pivot_wider(
  403.   long_df,
  404.   names_from = Attribute,
  405.   values_from = Value
  406. )
  407.  
  408. print(wide_df)
  409.  
  410.  
  411. # 10. Handle Missing Data and Detect Outliers
  412. df <- data.frame(
  413.   Name = c("Alice","Bob","Charlie","David","Eva","Frank"),
  414.   Age = c(22,25,NA,30,28,45),
  415.   Salary = c(35000,42000,39000,45000,150000,40000)
  416. )
  417.  
  418. print(df)
  419.  
  420. # Check missing values
  421. print(is.na(df))
  422.  
  423. # Count missing values
  424. print(colSums(is.na(df)))
  425.  
  426. # Remove rows with missing values
  427. clean_df <- na.omit(df)
  428.  
  429. cat("\nDataset after removing missing values:\n")
  430. print(clean_df)
  431.  
  432. # Replace missing values with mean
  433. mean_age <- mean(df$Age, na.rm = TRUE)
  434.  
  435. df$Age[is.na(df$Age)] <- mean_age
  436.  
  437. cat("\nDataset after replacing missing values:\n")
  438. print(df)
  439.  
  440. # Detect outliers
  441. boxplot(df$Salary,
  442.         main = "Salary Boxplot",
  443.         col = "lightblue")
  444.  
  445. outliers <- boxplot.stats(df$Salary)$out
  446.  
  447. cat("\nOutliers:\n")
  448. print(outliers)
  449.  
  450. # 11. Work with Dates and Times in R
  451. library(lubridate)
  452.  
  453. # Create dates and times
  454. dates <- c("2023-01-15", "2023-06-20", "2023-12-05")
  455. parsed_dates <- ymd(dates)
  456.  
  457. # Extract components
  458. years <- year(parsed_dates)
  459. months <- month(parsed_dates, label = TRUE)
  460. days <- day(parsed_dates)
  461.  
  462. # Date arithmetic
  463. date_diff <- parsed_dates[3] - parsed_dates[1]
  464.  
  465. cat("Parsed Dates:", as.character(parsed_dates), "\n")
  466. cat("Months:", as.character(months), "\n")
  467. cat("Difference in Days:", date_diff, "\n")
  468.  
  469.  
  470. # 12. Visualize Data Using ggplot2 (Bar, Scatter, Histogram, Boxplot)
  471. library(ggplot2)
  472.  
  473. data(mpg)
  474.  
  475. # Bar Plot
  476. ggplot(mpg, aes(x = class)) +
  477.   geom_bar(fill = "steelblue") +
  478.   theme_minimal() +
  479.   labs(title = "Bar Plot: Car Classes", x = "Class", y = "Count")
  480.  
  481. # Scatter Plot
  482. ggplot(mpg, aes(x = displ, y = hwy, color = class)) +
  483.   geom_point() +
  484.   theme_minimal() +
  485.   labs(title = "Scatter Plot: Engine Displacement vs Highway MPG")
  486.  
  487. # Histogram
  488. ggplot(mpg, aes(x = hwy)) +
  489.   geom_histogram(binwidth = 2, fill = "coral", color = "black") +
  490.   theme_minimal() +
  491.   labs(title = "Histogram: Highway MPG", x = "Highway MPG")
  492.  
  493. # Boxplot
  494. ggplot(mpg, aes(x = class, y = hwy, fill = class)) +
  495.   geom_boxplot() +
  496.   theme_minimal() +
  497.   labs(title = "Boxplot: Highway MPG by Class")
  498.  
  499.  
  500. # 13. Perform K-Means Clustering and Visualize Clusters
  501. library(ggplot2)
  502.  
  503. data(iris)
  504.  
  505. # Select numerical features
  506. iris_data <- iris[, 1:4]
  507.  
  508. # Perform K-Means clustering (k = 3)
  509. set.seed(123)
  510. kmeans_res <- kmeans(iris_data, centers = 3, nstart = 20)
  511.  
  512. # Add cluster labels to dataset
  513. iris$Cluster <- as.factor(kmeans_res$cluster)
  514.  
  515. # Visualize clusters
  516. ggplot(iris, aes(x = Sepal.Length, y = Sepal.Width, color = Cluster, shape = Cluster)) +
  517.   geom_point(size = 3) +
  518.   theme_minimal() +
  519.   labs(title = "K-Means Clustering on Iris Dataset")
  520.  
  521.  
  522. # 14. Evaluate Models Using Confusion Matrix, Accuracy, and ROC Curve
  523. library(caret)
  524. library(pROC)
  525.  
  526. data(iris)
  527. binary_iris <- iris[iris$Species != "setosa", ]
  528. binary_iris$Species <- droplevels(binary_iris$Species)
  529.  
  530. set.seed(123)
  531. train_idx <- createDataPartition(binary_iris$Species, p = 0.7, list = FALSE)
  532. train_data <- binary_iris[train_idx, ]
  533. test_data <- binary_iris[-train_idx, ]
  534.  
  535. model <- glm(Species ~ Sepal.Length + Sepal.Width, data = train_data, family = binomial)
  536. prob <- predict(model, newdata = test_data, type = "response")
  537. pred_class <- factor(ifelse(prob > 0.5, "virginica", "versicolor"), levels = levels(test_data$Species))
  538.  
  539. # Confusion Matrix & Accuracy
  540. conf_matrix <- confusionMatrix(pred_class, test_data$Species)
  541. print(conf_matrix)
  542.  
  543. # ROC Curve
  544. roc_curve <- roc(test_data$Species, prob)
  545. plot(roc_curve, col = "blue", main = "ROC Curve")
  546. cat("AUC:", auc(roc_curve), "\n")
  547.  
  548.  
  549. # 15. Perform Text Mining and Create a Word Cloud
  550. library(tm)
  551. library(wordcloud)
  552.  
  553. text_data <- c("R is a great language for data science and analytics.",
  554.                "Data visualization and machine learning with R are powerful.",
  555.                "Text mining in R allows easy analysis of unstructured text data.")
  556.  
  557. corpus <- Corpus(VectorSource(text_data))
  558. corpus <- tm_map(corpus, content_transformer(tolower))
  559. corpus <- tm_map(corpus, removePunctuation)
  560. corpus <- tm_map(corpus, removeNumbers)
  561. corpus <- tm_map(corpus, removeWords, stopwords("english"))
  562.  
  563. dtm <- TermDocumentMatrix(corpus)
  564. matrix <- as.matrix(dtm)
  565. words <- sort(rowSums(matrix), decreasing = TRUE)
  566. df <- data.frame(word = names(words), freq = words)
  567.  
  568. wordcloud(words = df$word, freq = df$freq, min.freq = 1,
  569.           max.words = 100, random.order = FALSE, colors = brewer.pal(8, "Dark2"))
  570.  
  571.  
  572. # 16. Time Series Forecasting with ARIMA on a real dataset
  573. library(forecast)
  574.  
  575. data("AirPassengers")
  576.  
  577. # Fit ARIMA model
  578. fit <- auto.arima(AirPassengers)
  579. summary(fit)
  580.  
  581. # Forecast next 12 months
  582. forecasted <- forecast(fit, h = 12)
  583.  
  584. # Plot forecast
  585. plot(forecasted, main = "AirPassengers ARIMA Forecast", xlab = "Year", ylab = "Passengers")
  586.  
  587.  
  588. # 17. Create interactive bar, line, and scatter plots using plotly
  589. library(plotly)
  590.  
  591. data(mtcars)
  592.  
  593. # Interactive Scatter Plot
  594. plot_ly(data = mtcars, x = ~wt, y = ~mpg, type = "scatter", mode = "markers", color = ~as.factor(cyl)) %>%
  595.   layout(title = "Interactive Scatter Plot: Weight vs MPG")
  596.  
  597. # Interactive Line Plot
  598. df_time <- data.frame(Day = 1:10, Sales = c(10, 15, 13, 18, 20, 25, 22, 30, 28, 35))
  599. plot_ly(data = df_time, x = ~Day, y = ~Sales, type = "scatter", mode = "lines+markers") %>%
  600.   layout(title = "Interactive Line Plot: Daily Sales")
  601.  
  602. # Interactive Bar Plot
  603. plot_ly(data = mtcars, x = ~as.factor(cyl), type = "histogram") %>%
  604.   layout(title = "Interactive Bar Plot: Cylinder Counts", xaxis = list(title = "Cylinders"))
  605.  
  606.  
  607. # 18. Develop a Shiny app that lets users upload a CSV file
  608. library(shiny)
  609.  
  610. ui <- fluidPage(
  611.   titlePanel("CSV File Uploader"),
  612.   sidebarLayout(
  613.     sidebarPanel(
  614.       fileInput("file1", "Choose CSV File", accept = ".csv"),
  615.       tags$hr(),
  616.       checkboxInput("header", "Header", TRUE)
  617.     ),
  618.     mainPanel(
  619.       tableOutput("contents")
  620.     )
  621.   )
  622. )
  623.  
  624. server <- function(input, output) {
  625.   output$contents <- renderTable({
  626.     req(input$file1)
  627.     read.csv(input$file1$datapath, header = input$header)
  628.   })
  629. }
  630.  
  631. shinyApp(ui = ui, server = server)
Advertisement
Add Comment
Please, Sign In to add comment