cl1p.net - The internet clipboard
cl1p.net Discord
Login/Sign Up
cl1p.net/abcd
cl1p.net/abcd
cl1p.net Discord
Login/Sign Up
This cl1p will be deleted in in 5 hours.
Copy
9.Experiment the steps to connect with a data source and choose between live connection and extract. CODE: Part A: Regression Program # Sample Dataset crop_data <- data.frame( Fertilizer = c(10, 20, 30, 40, 50, 60, 70), Yield = c(20,40,60,80,100,120,140) ) print(crop_data) # View dataset print(crop_data) # Fit regression model model <- lm(Yield ~ Fertilizer, data = crop_data) # Show summary summary(model) # Plot with regression line plot(crop_data$Fertilizer, crop_data$Yield, main = "Crop Yield vs Fertilizer", xlab = "Fertilizer Amount", ylab = "Crop Yield", pch = 19, col = "blue") abline(model, col = "red", lwd = 2) Part B: Data Source Connection # Install packages if needed install.packages("DBI") install.packages("RSQLite") library(DBI) library(RSQLite) # Connect to SQLite database (live connection) con <- dbConnect(RSQLite::SQLite(), "my_database.sqlite") # Write table into database dbWriteTable(con, "crops", crop_data, overwrite = TRUE) # Query data (live connection) live_data <- dbGetQuery(con, "SELECT * FROM crops") print(live_data) # Extract data into R (snapshot) extract_data <- live_data print(extract_data) # Disconnect from database dbDisconnect(con) 10.Program to Add Web Images Dynamically to Worksheets CODE: # install.packages(c("ggplot2", "ggimage")) library(ggplot2) library(ggimage) # 2. Create the dataset using LOCAL paths. languages_data <- data.frame( Subject = c("Java", "Python", "R"), YearStarted = c(1995, 1991, 1993), Image = c( "C:\\Users\\vvina\\OneDrive\\Documents\\My Tableau Repository\\Shapes\\languages\\java.png", "C:\\Users\\vvina\\OneDrive\\Documents\\My Tableau Repository\\Shapes\\languages\\python.jpeg", "C:\\Users\\vvina\\OneDrive\\Documents\\My Tableau Repository\\Shapes\\languages\\r.png" ) ) # 3. Generate the plot ggplot(languages_data, aes(x = YearStarted, y = Subject)) + geom_image(aes(image = Image), size = 0.1) + xlim(1988, 2000) + labs( title = "Programming Languages & Launch Years", x = "Year Started", y = "Language" ) + theme_minimal() + theme( axis.text = element_text(size = 12, face = "bold"), plot.title = element_text(size = 14, face = "bold", hjust = 0.5)) 11.Program to Organize and Customize Fields in the Data Pane. CODE: # install.packages("dplyr") # install.packages("ggplot2") library(dplyr) library(ggplot2) students <- data.frame( Name = c("Amit", "Bhavana", "Chetan", "Divya", "Amit", "Bhavana"), Subject = c("Java", "Python", "R", "Java", "Python", "R"), Marks = c(85, 92, 78, 90, 88, 95), Department = c("CSE", "ISE", "CSE", "ISE", "CSE", "ISE") ) print(students) str(students) # Rename a Field students <- students %>% rename(Student_Marks = Marks) # Create a Folder / Structure # by selecting and grouping columns cleanly. academic_details <- students %>% select (Name, Subject, Student_Marks, Department) # Hide an Unnecessary Field # To hide or drop a column in R, we use select() with a minus (-) sign cleaned_data <- academic_details %>% select(-Department) print(cleaned_data) 12.Perform Maps and Geographic Data Analysis CODE: # install.packages(c("ggplot2", "dplyr", "maps")) library(ggplot2) library(dplyr) library(maps) city_sales <- data.frame( City = c("bengaluru", "mysuru", "mumbai", "pune", "chennai"), State = c("karnataka", "karnataka", "maharashtra", "maharashtra", "tamil nadu"), Sales = c(95000, 42000, 120000, 68000, 85000) ) # Fetch Geographic Coordinates (Geographic Role) # We load the coordinates of India's states or standard city maps. geo_data <- data.frame( City = c("bengaluru", "mysuru", "mumbai", "pune", "chennai"), lon = c(77.5946, 76.6394, 72.8777, 73.8567, 80.2707), lat = c(12.9716, 12.2958, 19.0760, 18.5204, 13.0827) ) # Combine sales data with geographic coordinates based on 'City' final_map_data <- merge(city_sales, geo_data, by = "City") # Get the background map outlines india_map <- map_data("world", region = "India") # Plotting the Map Layout ggplot() + geom_polygon(data = india_map, aes(x = long, y = lat, group = group), fill = "gray95", color = "gray70") + # Display Cities on the Map and map Sales to Color geom_point(data = final_map_data, aes(x = lon, y = lat, color = Sales), size = 6, alpha = 0.9) + # Step 7: Display Sales Labels directly on the map coordinates geom_text(data = final_map_data, aes(x = lon, y = lat, label = paste0(City, "\n ", Sales)), vjust = -1.2, fontface = "bold", size = 3.5) + # Apply a professional color gradient (Darker blue = Higher Sales) scale_color_gradient(low = "skyblue", high = "darkblue") + # Crop the visualization window to focus exactly on our data regions coord_fixed(xlim = c(70, 85), ylim = c(10, 22)) + # Clean styling suited for geospatial dashboards labs( title = "Geographic Distribution of Sales Performance", subtitle = "Analysis by State and City Markets", color = "Sales Value (Measure)" ) + theme_minimal() + theme( axis.title = element_blank(), axis.text = element_blank(), axis.ticks = element_blank(), panel.grid = element_blank(), plot.title = element_text(size = 14, face = "bold", hjust = 0.5), plot.subtitle = element_text(size = 11, hjust = 0.5) ) 13.Perform quick table calculations including creating calculated fields, calculating moving averages, and computing percentages of the total CODE: # install.packages(c("ggplot2", "zoo", "dplyr",)) library(ggplot2) library(zoo) library(dplyr) sales_data <- data.frame( Month=factor(c("Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep"," Oct","Nov","Dec"), levels = c("Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct ","Nov","Dec")), Sales = c(1200, 1500, 1800, 2000, 2200, 2500, 2700, 3000, 2800, 3200, 3500, 4000) ) # 2. Combined Calculated Fields (Custom, Moving Avg, and % of Total) analytical_data <- sales_data %>% mutate( Bonus_Sales = Sales * 1.10, Moving_Avg = rollmean(Sales, k = 3, fill = NA, align = "right"), Pct_Total = (Sales / sum(Sales)) * 100 ) print(analytical_data) # 3. Time Series Line Visualization ggplot(analytical_data, aes(x = Month, group = 1)) + geom_line(aes(y = Sales), color = "gray60", linetype = "dashed", size = 1) + geom_line(aes(y = Moving_Avg), color = "darkblue", size = 1.2) + geom_point(aes(y = Moving_Avg), color = "darkblue", size = 2.5) + labs(title = "Sales & 3-Month Moving Average", x = "Month", y = "Value") + theme_minimal() + theme(plot.title = element_text(face = "bold", hjust = 0.5)) 14.Write a program to apply filters to dimensions and measures CODE: Name <- c("Ram","Sita","Arun","Ashok","Vinay","Nani","Rahul","Priya","Ki ran","Meena") Department <-c("CSE","CSE","ISE","ECE","CSE","ISE","CSE","ECE","ISE","CSE") Marks <- c(85,90,78,88,82,76,91,87,80,84) students <- data.frame(Name, Department, Marks) print(students) cse_students <- students[students$Department == "CSE", ] print(cse_students) high_marks <- students[students$Marks > 85, ] print(high_marks) result <- students[students$Department == "CSE" & students$Marks > 85, ] print(result) 15.Design a program to Map a data geographically CODE: # install.packages(c("ggplot2","maps")) library(ggplot2) library(maps) # 1. Data with city coordinates city <- c("Bangalore","Hyderabad","Chennai","Mumbai","Delhi","Kolkata"," Pune","Ahmedabad","Jaipur","Mysore") sales <- c(1200,1500,1300,2000,2200,1400,1100,900,700,800) lat <- c(12.97,17.38,13.08,19.07,28.61,22.57,18.52,23.03,26.92,12.30) long <- c(77.59,78.49,80.27,72.88,77.23,88.36,73.85,72.58,75.79,76.64) data <- data.frame(city, sales, lat, long) print(data) # 2. India map world_map <- map_data("world") india_map <- subset(world_map, region == "India") # 3. Plot India map + city sales ggplot(india_map, aes(long, lat)) + geom_polygon(aes(group = group), fill = "orange", color = "black") + geom_point(data = data, aes(long, lat, size = sales), color = "red", alpha = 0.7) + geom_text(data = data, aes(long, lat, label = city), vjust = -1, size = 3) + labs(title = "Sales Data Mapped to Indian Cities") + theme_minimal() 16.Create a chart, dashboards and Stories CODE: # Install packages (run only once) install.packages("shiny") install.packages("shinydashboard") install.packages("ggplot2") install.packages("plotly") # Load packages library(shiny) library(shinydashboard) library(ggplot2) library(plotly) # Create sample data sales <- data.frame( Month = c("Jan", "Feb", "Mar", "Apr", "May"), Sales = c(1000, 1500, 1200, 1800, 2000), Profit = c(200, 300, 250, 400, 500) ) # UI: Create dashboard layout ui <- dashboardPage( dashboardHeader(title = "Charts Dashboard"), dashboardSidebar( sidebarMenu( menuItem("Dashboard", tabName = "dashboard") ) ), dashboardBody( tabItems( tabItem( tabName = "dashboard", # Display two charts side by side fluidRow( box( plotlyOutput("salesChart"), width = 6 ), box( plotlyOutput("profitChart"), width = 6 ) ), # Display story fluidRow( box( width = 12, h3("Story"), p("Sales and profit increase gradually from January to May.") ) ) ) ) ) ) # Server: Generate charts server <- function(input, output) { # Monthly Sales Bar Chart output$salesChart <- renderPlotly({ p <- ggplot( sales, aes(x = Month, y = Sales, fill = Month) ) + geom_bar(stat = "identity") + ggtitle("Monthly Sales Chart") ggplotly(p) }) # Monthly Profit Line Chart output$profitChart <- renderPlotly({ p <- ggplot( sales, aes(x = Month, y = Profit, group = 1) ) + geom_line() + geom_point() + ggtitle("Monthly Profit Chart") ggplotly(p) }) } # Run the application shinyApp(ui, server) 17.Write a program to add interactivity and formatting to dashboards Code: # Install packages (run only once) install.packages("shiny") install.packages("shinydashboard") install.packages("plotly") install.packages("ggplot2") # Load packages library(shiny) library(shinydashboard) library(plotly) library(ggplot2) # Create sample data sales <- data.frame( Month = c("Jan", "Feb", "Mar", "Apr", "May"), Sales = c(1000, 1500, 1200, 1800, 2000), Profit = c(200, 300, 250, 400, 500) ) # UI: Create dashboard layout ui <- dashboardPage( dashboardHeader(title = "Interactive Dashboard"), dashboardSidebar( sliderInput( "salesfilter", "Select Minimum Sales", min = 1000, max = 2000, value = 1000 ) ), dashboardBody( # Display charts fluidRow( box( plotlyOutput("salesPlot"), width = 6, background = "light-blue" ), box( plotlyOutput("profitPlot"), width = 6, background = "green" ) ), # Display total sales and profit fluidRow( valueBoxOutput("totalSales"), valueBoxOutput("totalProfit") ) ) ) # Server: Process data and generate outputs server <- function(input, output) { # Filter sales data based on slider value filtered_data <- reactive({ sales[sales$Sales >= input$salesfilter, ] }) # Interactive Sales Chart output$salesPlot <- renderPlotly({ p <- ggplot( filtered_data(), aes(x = Month, y = Sales, fill = Month) ) + geom_bar(stat = "identity") + ggtitle("Interactive Sales Chart") ggplotly(p) }) # Interactive Profit Chart output$profitPlot <- renderPlotly({ p <- ggplot( filtered_data(), aes(x = Month, y = Profit, group = 1) ) + geom_line() + geom_point(size = 3) + ggtitle("Profit Trend") ggplotly(p) }) # Display Total Sales output$totalSales <- renderValueBox({ valueBox( sum(filtered_data()$Sales), "Total Sales", icon = icon("chart-bar"), color = "blue" ) }) # Display Total Profit output$totalProfit <- renderValueBox({ valueBox( sum(filtered_data()$Profit), "Total Profit", icon = icon("money-bill"), color = "green" ) }) } # Run the application shinyApp(ui, server)