### Load RLightGBM Library Source: https://github.com/thealgorithms/r/blob/master/documentation/light_gbm.md Loads the RLightGBM package. This is a prerequisite for using any of its functions. The example shows a common error if the package is not installed. ```r library(RLightGBM) ``` -------------------------------- ### Install and Use dbscan Package in R Source: https://github.com/thealgorithms/r/blob/master/documentation/dbscan_clustering.html This snippet demonstrates how to load the 'dbscan' library in R. It also shows an example of performing DBSCAN clustering on the iris dataset and plotting the results. Note that the provided code assumes the 'dbscan' package is successfully installed. ```r library(dbscan) # Perform DBSCAN clustering # The input data is iris[,-5] (features of iris dataset) # eps is the maximum distance between two points for one to be considered as in the neighborhood of the other. # minPts is the number of points in a neighborhood for a point to be considered as a core point. cl <- dbscan(iris[, -5], eps = .5, minPts = 5) # Plot the results, coloring points by their cluster assignment plot(iris[, -5], col = cl$cluster) ``` -------------------------------- ### Create LightGBM Booster in R Source: https://github.com/thealgorithms/r/blob/master/documentation/light_gbm.md Initializes the LightGBM booster model using the prepared data handle and configuration. The `lgbm.booster.create` function sets up the model structure. The example indicates the function is unavailable. ```r handle.booster <- lgbm.booster.create(handle.data, lapply(config, as.character)) ``` -------------------------------- ### Load Example Data in R Source: https://github.com/thealgorithms/r/blob/master/documentation/light_gbm.md Attempts to load example binary classification data. This function is used to access built-in datasets for testing. The example demonstrates a 'not found' warning. ```r data(example.binary) ``` -------------------------------- ### Configure and Create LightGBM Data Handle in R Source: https://github.com/thealgorithms/r/blob/master/documentation/light_gbm.md Sets up parameters for LightGBM training and creates a data handle. The `lgbm.data.create` function initializes a data structure for the model. The example shows an error indicating the function is not found. ```r #Parameters num_iterations <- 100 config <- list(objective = "binary", metric="binary_logloss,auc", learning_rate = 0.1, num_leaves = 63, tree_learner = "serial", feature_fraction = 0.8, bagging_freq = 5, bagging_fraction = 0.8, min_data_in_leaf = 50, min_sum_hessian_in_leaf = 5.0) #Create data handle and booster handle.data <- lgbm.data.create(x) ``` -------------------------------- ### Load KNN Library in R Source: https://github.com/thealgorithms/r/blob/master/documentation/knn.html This snippet attempts to load the 'knn' library in R. It's a prerequisite for using KNN functions. The error message indicates that the package is not installed, which is a common issue. ```r library(knn) ## Error in library(knn): there is no package called 'knn' ``` -------------------------------- ### Test DFS from Different Starting Vertex in R Source: https://github.com/thealgorithms/r/blob/master/documentation/depth_first_search.md Demonstrates testing the recursive DFS algorithm in R from a different starting vertex (2) on the sample graph. It calls `depth_first_search` and prints the traversal order, showing how the starting point affects the DFS path. ```r # Test with different starting vertex cat("\nRecursive DFS starting from vertex 2:\n") ``` ```r result_from_2 <- depth_first_search(graph, 2) cat("Traversal order:", paste(result_from_2, collapse = " -> "), "\n") ``` -------------------------------- ### Example Graph and BFS Usage in R Source: https://github.com/thealgorithms/r/blob/master/documentation/breadth_first_search.md Demonstrates the usage of the BFS algorithms by defining a sample graph as an adjacency list and printing its structure. This section serves as an example for how to input graph data and initiate BFS functions. ```r # Create a sample graph as adjacency list # Graph structure: # 1 # / \ # 2 3 # / \ \ # 4 5 6 graph <- list( "1" = c(2, 3), "2" = c(4, 5), "3" = c(6), "4" = c(), "5" = c(), "6" = c() ) cat("Graph structure (adjacency list):\n") for (vertex in names(graph)) { cat("Vertex", vertex, "-> [", paste(graph[[vertex]], collapse = ", "), "]\n") } ``` -------------------------------- ### Load RLightGBM Library and Data Source: https://github.com/thealgorithms/r/blob/master/documentation/light_gbm.html This snippet attempts to load the RLightGBM library and a sample dataset named 'example.binary'. It includes error handling for cases where the package or data is not found. The primary purpose is to set up the environment for subsequent RLightGBM operations. ```r library(RLightGBM) ## Error in library(RLightGBM): there is no package called 'RLightGBM' data(example.binary) ## Warning in data(example.binary): data set 'example.binary' not found ``` -------------------------------- ### Example Usage of Dijkstra's Algorithm in R Source: https://github.com/thealgorithms/r/blob/master/documentation/dijkstra_shortest_path.html Demonstrates how to use the implemented Dijkstra's algorithm. It defines a sample weighted graph, runs the algorithm from a specified source vertex, and then prints the shortest distances to all reachable vertices. This section serves as a practical guide and test case for the algorithm. ```R # Example usage and testing cat("=== Dijkstra's Shortest Path Algorithm ===\n") # Create a weighted graph as adjacency list # Graph structure with weights: # 1 # / \ # 4/ \2 # / \ # 2 3 # |3 /1 # | / # 4-----5 # 2 weighted_graph <- list( "1" = list( list(vertex = 2, weight = 4), list(vertex = 3, weight = 2) ), "2" = list( list(vertex = 4, weight = 3) ), "3" = list( list(vertex = 5, weight = 1) ), "4" = list( list(vertex = 5, weight = 2) ), "5" = list() ) cat("Weighted graph structure:\n") for (vertex in names(weighted_graph)) { edges <- weighted_graph[[vertex]] if (length(edges) > 0) { edge_strs <- sapply(edges, function(e) paste0(e$vertex, "(", e$weight, ")")) cat("Vertex", vertex, "-> [", paste(edge_strs, collapse = ", "), "]\n") } else { cat("Vertex", vertex, "-> []\n") } } # Run Dijkstra's algorithm from vertex 1 cat("\nRunning Dijkstra's algorithm from vertex 1:\n") result <- dijkstra_shortest_path(weighted_graph, 1) # Display shortest distances cat("Shortest distances from vertex 1:\n") for (i in 1:length(result$distances)) { if (result$distances[i] != Inf) { cat("To vertex", i, ": distance =", result$distances[i], "\n") } } ``` -------------------------------- ### Save LightGBM Model in R Source: https://github.com/thealgorithms/r/blob/master/documentation/light_gbm.html This snippet demonstrates how to save a trained LightGBM booster model to a file. The saved model can be reloaded later using 'lgbm.booster.load'. It requires the booster handle and a filename. ```r lgbm.booster.save(handle.booster, filename = "/tmp/model.txt") ``` -------------------------------- ### Save LightGBM Model in R Source: https://github.com/thealgorithms/r/blob/master/documentation/light_gbm.md Saves the trained LightGBM model to a file for later use. The `lgbm.booster.save` function allows persistence of the model. The example demonstrates an error because the function is not available. ```r #Save model (can be loaded again via lgbm.booster.load(filename)) lgbm.booster.save(handle.booster, filename = "/tmp/model.txt") ``` -------------------------------- ### Train LightGBM Model in R Source: https://github.com/thealgorithms/r/blob/master/documentation/light_gbm.md Trains the LightGBM model for a specified number of iterations and evaluates performance at regular intervals. The `lgbm.booster.train` function performs the training process. The example shows an error due to the function not being found. ```r #Train for num_iterations iterations and eval every 5 steps lgbm.booster.train(handle.booster, num_iterations, 5) ``` -------------------------------- ### Predict with LightGBM Model in R Source: https://github.com/thealgorithms/r/blob/master/documentation/light_gbm.html This snippet shows how to make predictions using a trained LightGBM booster handle. It requires the 'lgbm.booster.predict' function and the booster handle along with test data. ```r pred <- lgbm.booster.predict(handle.booster, x.test) ``` -------------------------------- ### Predict with LightGBM Model in R Source: https://github.com/thealgorithms/r/blob/master/documentation/light_gbm.md Generates predictions on new data using the trained LightGBM booster. The `lgbm.booster.predict` function takes the booster handle and test data as input. The example shows an error indicating the function is missing. ```r #Predict pred <- lgbm.booster.predict(handle.booster, x.test) ``` -------------------------------- ### Example Graph Visualization in R Source: https://github.com/thealgorithms/r/blob/master/documentation/dijkstra_shortest_path.md Demonstrates how to create and print a weighted graph using an adjacency list representation in R. This is used to test the Dijkstra's algorithm implementation. ```r # Create a weighted graph as adjacency list # Graph structure with weights: # 1 # / \ # 4/ \2 # / \ # 2 3 # |3 /1 # | / # 4-----5 # 2 weighted_graph <- list( "1" = list( list(vertex = 2, weight = 4), list(vertex = 3, weight = 2) ), "2" = list( list(vertex = 4, weight = 3) ), "3" = list( list(vertex = 5, weight = 1) ), "4" = list( list(vertex = 5, weight = 2) ), "5" = list() ) cat("Weighted graph structure:\n") ``` ```r for (vertex in names(weighted_graph)) { edges <- weighted_graph[[vertex]] if (length(edges) > 0) { edge_strs <- sapply(edges, function(e) paste0(e$vertex, "(", e$weight, ")")) cat("Vertex", vertex, "-> [", paste(edge_strs, collapse = ", "), "]\n") } else { cat("Vertex", vertex, "-> []\n") } } ``` -------------------------------- ### Load randomForest Library in R Source: https://github.com/thealgorithms/r/blob/master/documentation/random_forest.html This snippet attempts to load the 'randomForest' library in R. It's a prerequisite for using random forest models. The example includes a common error message indicating the package is not installed or found. ```r library(randomForest) ## Error in library(randomForest): there is no package called 'randomForest' ``` -------------------------------- ### Load KNN Library in R Source: https://github.com/thealgorithms/r/blob/master/documentation/knn.md This snippet attempts to load the 'knn' package in R. It's a prerequisite for using KNN functions. The example shows a common error if the package is not installed. ```r library(knn) ``` -------------------------------- ### Load xlsx Package in R Source: https://github.com/thealgorithms/r/blob/master/documentation/data_processing.html Loads the 'xlsx' package, which is required for reading and writing Excel files. It also loads 'rJava' and 'xlsxjars' as dependencies. If the package is not installed, an error will occur. ```r library(xlsx) ## Error in library(xlsx): there is no package called 'xlsx' ## Loading required package: rJava ## Loading required package: xlsxjars ``` -------------------------------- ### Install and Load R6 Package for BST Node Implementation in R Source: https://github.com/thealgorithms/r/blob/master/documentation/binary_search_tree.md This R code snippet checks if the 'R6' package is installed and loads it. If not installed, it proceeds to install the package. The 'R6' package is essential for defining the BSTNode class, enabling object-oriented programming features for the BST implementation. ```r # Define BST Node structure using R6 class system if (!require(R6, quietly = TRUE)) { cat("Installing R6 package for object-oriented programming...\n") install.packages("R6", quiet = TRUE) library(R6) } ``` -------------------------------- ### Example Usage of Coin Change in R Source: https://github.com/thealgorithms/r/blob/master/documentation/coin_change.html Demonstrates the usage of the coin_change function with various test cases. It includes basic examples, a case where no solution is possible, and a test with a larger dataset to verify the algorithm's correctness. ```R # Example Usage & Testing cat("=== Coin Change Problem ===\n\n") # Test 1: Basic Example coins <- c(1, 2, 5) amount <- 11 cat("Coins:", paste(coins, collapse = ", "), "\n") cat("Amount:", amount, "\n") min_coins <- coin_change(coins, amount) cat("Minimum Coins Needed:", min_coins, "\n\n") # Test 2: No solution case coins <- c(2, 4) amount <- 7 cat("Coins:", paste(coins, collapse = ", "), "\n") cat("Amount:", amount, "\n") min_coins <- coin_change(coins, amount) cat("Minimum Coins Needed:", min_coins, "\n\n") # Test 3: Larger dataset coins <- c(1, 3, 4, 5) amount <- 7 cat("Coins:", paste(coins, collapse = ", "), "\n") cat("Amount:", amount, "\n") min_coins <- coin_change(coins, amount) cat("Minimum Coins Needed:", min_coins, "\n\n") ``` -------------------------------- ### R BST: Insert, Get Size, Height, and Validate Source: https://github.com/thealgorithms/r/blob/master/documentation/binary_search_tree.html This snippet shows how to initialize a BST, insert values, and retrieve its size, height, and validity. It assumes a BST class with `new()`, `insert()`, `get_size()`, `height()`, and `is_valid_bst()` methods. ```R bst <- BST$new() # Insert values values <- c(50, 30, 70, 20, 40, 60, 80) cat("Inserting values:", paste(values, collapse = ", "), "\n") for (value in values) { bst$insert(value) } cat("Tree size:", bst$get_size(), "\n") cat("Tree height:", bst$height(), "\n") cat("Is valid BST:", bst$is_valid_bst(), "\n\n") ``` -------------------------------- ### Sorting Data Frames with plyr Package in R Source: https://github.com/thealgorithms/r/blob/master/documentation/data_processing.html This R snippet shows how to sort a data frame using the `arrange` function from the `plyr` package. It demonstrates sorting in ascending and descending order. Note that the `plyr` package needs to be installed and loaded before use. ```r # Sort using the arrange function of the plyr package library(plyr) arrange(X, var1) arrange(X, desc(var1)) ``` -------------------------------- ### Load Training Data in R Source: https://github.com/thealgorithms/r/blob/master/documentation/linear_regression.md Loads training input variables into `x_train`. Assumes `input_variables_values_training_datasets` is a pre-defined numeric numpy array. This step is crucial for preparing data for model training. ```r # Load Train and Test datasets # Identify feature and response variable(s) and values must be numeric and numpy arrays x_train <- input_variables_values_training_datasets ``` -------------------------------- ### Display First Few Rows of Data Frame in R Source: https://github.com/thealgorithms/r/blob/master/documentation/data_processing.html Displays the first few rows of the `cameraData` data frame. This is useful for quickly inspecting the structure and content of the data after reading it from a file. An error occurs if the `cameraData` object is not found. ```r head(cameraData) ## Error in head(cameraData): object 'cameraData' not found ## address direction street crossStreet ## 1 S CATON AVE & BENSON AVE N/B Caton Ave Benson Ave ## 2 S CATON AVE & BENSON AVE S/B Caton Ave Benson Ave ## 3 WILKENS AVE & PINE HEIGHTS AVE E/B Wilkens Ave Pine Heights ## 4 THE ALAMEDA & E 33RD ST S/B The Alameda 33rd St ## 5 E 33RD ST & THE ALAMEDA E/B E 33rd The Alameda ## 6 ERDMAN AVE & N MACON ST E/B Erdman Macon St ``` -------------------------------- ### Set Label Field for LightGBM Data in R Source: https://github.com/thealgorithms/r/blob/master/documentation/light_gbm.md Assigns the target variable (label) to the LightGBM data handle. This is crucial for supervised learning. The example shows an error as the function is not found. ```r lgbm.data.setField(handle.data, "label", y) ``` -------------------------------- ### Creating a Function in R Source: https://github.com/thealgorithms/r/blob/master/documentation/kmeans_clustering.html Provides an example of how to define and use a custom function in R. Functions are reusable blocks of code that perform specific tasks. ```r my_function <- function(x, y) { return(x + y) } result <- my_function(5, 3) print(result) ``` -------------------------------- ### Load Test Data in R Source: https://github.com/thealgorithms/r/blob/master/documentation/linear_regression.md Loads the test input variables into `x_test`. This dataset is used to evaluate the trained model's performance on unseen data. It should be in a format compatible with the training data. ```r x_test <- input_variables_values_test_datasets ``` -------------------------------- ### Create and Display Cyclic Graph in R Source: https://github.com/thealgorithms/r/blob/master/documentation/depth_first_search.md Illustrates the creation of a cyclic graph using an adjacency list in R. It then prints the structure of this cyclic graph, similar to the previous example, to visualize the connections before applying DFS. ```r # Example with a more complex graph (with cycles) cat("\n=== Example with Cyclic Graph ===\n") ``` ```r cyclic_graph <- list( "1" = c(2, 3), "2" = c(1, 4), "3" = c(1, 5), "4" = c(2, 6), "5" = c(3, 6), "6" = c(4, 5) ) cat("Cyclic graph structure:\n") ``` ```r for (vertex in names(cyclic_graph)) { cat("Vertex", vertex, "-> [", paste(cyclic_graph[[vertex]], collapse = ", "), "]\n") } ``` -------------------------------- ### BST Size and Emptiness Check Methods in R Source: https://github.com/thealgorithms/r/blob/master/documentation/binary_search_tree.md Provides methods to get the total number of nodes in the BST (`get_size`) and to check if the tree is currently empty (`is_empty`). ```r get_size = function() { return(self$size) } is_empty = function() { return(is.null(self$root)) } ``` -------------------------------- ### Load e1071 Package in R Source: https://github.com/thealgorithms/r/blob/master/documentation/naive_bayes.md Loads the 'e1071' library, which is necessary for using Naive Bayes and other machine learning functions in R. This step might fail if the package is not installed. ```r library(e1071) ``` -------------------------------- ### Load R Libraries Source: https://github.com/thealgorithms/r/blob/master/documentation/xgboost.md Loads the 'tidyverse' and 'xgboost' libraries. These libraries are essential for data manipulation and gradient boosting machine learning, respectively. Ensure these packages are installed before running. ```r library(tidyverse) library(xgboost) ``` -------------------------------- ### Load e1071 Library in R Source: https://github.com/thealgorithms/r/blob/master/documentation/naive_bayes.html This snippet demonstrates how to load the 'e1071' library in R, which is commonly used for statistical computations and machine learning algorithms. It includes a common error message indicating that the package is not installed. ```r library(e1071) ## Error in library(e1071): there is no package called 'e1071' ``` -------------------------------- ### Configure and Initialize RLightGBM Model Source: https://github.com/thealgorithms/r/blob/master/documentation/light_gbm.html This section demonstrates setting up configuration parameters for an RLightGBM model, specifically for binary classification. It then proceeds to create a data handle and a booster handle, which are essential objects for training the LightGBM model. Errors indicate that the necessary functions are not available, likely due to the RLightGBM package not being loaded correctly. ```r #Parameters num_iterations <- 100 config <- list(objective = "binary", metric="binary_logloss,auc", learning_rate = 0.1, num_leaves = 63, tree_learner = "serial", feature_fraction = 0.8, bagging_freq = 5, bagging_fraction = 0.8, min_data_in_leaf = 50, min_sum_hessian_in_leaf = 5.0) #Create data handle and booster handle.data <- lgbm.data.create(x) ## Error in lgbm.data.create(x): could not find function "lgbm.data.create" lgbm.data.setField(handle.data, "label", y) ## Error in lgbm.data.setField(handle.data, "label", y): could not find function "lgbm.data.setField" handle.booster <- lgbm.booster.create(handle.data, lapply(config, as.character)) ## Error in lgbm.booster.create(handle.data, lapply(config, as.character)): could not find function "lgbm.booster.create" ``` -------------------------------- ### Sorting and Ordering Data in R Source: https://github.com/thealgorithms/r/blob/master/documentation/data_processing.md Provides examples of sorting and ordering data within an R data frame. `sort()` is used for vectors, while `order()` is used to get the index for reordering rows of a data frame. It demonstrates sorting in ascending and descending order, handling `NA` values during sorting, and multi-column ordering. It also shows an attempt to use `arrange` from the `plyr` package, which requires the package to be installed and loaded. ```r # Sorting sort(X$var1) sort(X$var1, decreasing = TRUE) sort(X$var2, na.last = TRUE) # Ordering X[order(X$var1), ] X[order(X$var1, X$var3), ] ## Sort using the arrange function of the plyr package library(plyr) arrange(X, var1) arrange(X, desc(var1)) ``` -------------------------------- ### Graph Definition and DFS Testing in R Source: https://github.com/thealgorithms/r/blob/master/documentation/depth_first_search.html Defines a sample graph using an adjacency list and demonstrates the usage of both recursive and iterative DFS functions. It prints the graph structure and the traversal order for different starting vertices and graph types. ```r # Create a sample graph as adjacency list # Graph structure: # 1 # / \ # 2 3 # / \ \ # 4 5 6 graph <- list( "1" = c(2, 3), "2" = c(4, 5), "3" = c(6), "4" = c(), "5" = c(), "6" = c() ) cat("Graph structure (adjacency list):\n") for (vertex in names(graph)) { cat("Vertex", vertex, "-> [", paste(graph[[vertex]], collapse = ", "), "]\n") } # Test recursive DFS cat("\nRecursive DFS starting from vertex 1:\n") result_recursive <- depth_first_search(graph, 1) cat("Traversal order:", paste(result_recursive, collapse = " -> "), "\n") # Test iterative DFS cat("\nIterative DFS starting from vertex 1:\n") result_iterative <- dfs_iterative(graph, 1) cat("Traversal order:", paste(result_iterative, collapse = " -> "), "\n") # Test with different starting vertex cat("\nRecursive DFS starting from vertex 2:\n") result_from_2 <- depth_first_search(graph, 2) cat("Traversal order:", paste(result_from_2, collapse = " -> "), "\n") # Example with a more complex graph (with cycles) cat("\n=== Example with Cyclic Graph ===\n") cyclic_graph <- list( "1" = c(2, 3), "2" = c(1, 4), "3" = c(1, 5), "4" = c(2, 6), "5" = c(3, 6), "6" = c(4, 5) ) cat("Cyclic graph structure:\n") for (vertex in names(cyclic_graph)) { cat("Vertex", vertex, "-> [", paste(cyclic_graph[[vertex]], collapse = ", "), "]\n") } cat("\nDFS on cyclic graph starting from vertex 1:\n") cyclic_result <- depth_first_search(cyclic_graph, 1) cat("Traversal order:", paste(cyclic_result, collapse = " -> "), "\n") ``` -------------------------------- ### Running Linked List Demonstrations in R Source: https://github.com/thealgorithms/r/blob/master/linked_list_algorithms/README.md Provides code to execute the demonstration functions for each type of linked list implementation in R. This allows users to see the algorithms in action with step-by-step output. Requires the respective .r files for each linked list type. ```r # Singly Linked List examples source("singly_linked_list.r") demonstrate_singly_linked_list() # Doubly Linked List examples source("doubly_linked_list.r") demonstrate_doubly_linked_list() # Circular Linked List examples source("circular_linked_list.r") demonstrate_circular_linked_list() ``` -------------------------------- ### Get All Shortest Paths from a Vertex in R Source: https://github.com/thealgorithms/r/blob/master/documentation/dijkstra_shortest_path.html This R code snippet calculates and prints all shortest paths from a specified starting vertex to all other reachable vertices in a graph. It utilizes a `get_all_shortest_paths` function and iterates through the results to display each path and its distance. ```r cat("\nAll shortest paths from vertex 1:\n") all_paths <- get_all_shortest_paths(result, 1) for (target in names(all_paths)) { path_info <- all_paths[[target]] cat("To vertex", target, ": ", paste(path_info$path, collapse = " -> "), " (distance:", path_info$distance, ")\n") } ``` -------------------------------- ### Train and Predict with RLightGBM Model Source: https://github.com/thealgorithms/r/blob/master/documentation/light_gbm.html This code snippet illustrates the process of training an RLightGBM model for a specified number of iterations and evaluating its performance at regular intervals. It also includes a placeholder for prediction. Similar to the previous snippets, errors are encountered, indicating that the training and prediction functions are not accessible. ```r #Train for num_iterations iterations and eval every 5 steps lgbm.booster.train(handle.booster, num_iterations, 5) ## Error in lgbm.booster.train(handle.booster, num_iterations, 5): could not find function "lgbm.booster.train" #Predict ``` -------------------------------- ### Read Specific Rows and Columns from Excel in R Source: https://github.com/thealgorithms/r/blob/master/documentation/data_processing.html This snippet demonstrates how to read a specific subset of data from an Excel file using the `read.xlsx` function. It specifies the column and row indices to be extracted. Note that the `read.xlsx` function might require the `xlsx` package to be installed and loaded. ```r # Read specific rows and columns in Excel colIndex <- 2:3 rowIndex <- 1:4 cameraDataSubset <- read.xlsx("./data/cameras.xlsx", sheetIndex = 1, colIndex = colIndex, rowIndex = rowIndex) ``` -------------------------------- ### Create and Display Sample Graph in R Source: https://github.com/thealgorithms/r/blob/master/documentation/depth_first_search.md Demonstrates how to create a sample graph using an adjacency list representation in R. It then iterates through the list to print the structure of the graph, showing each vertex and its connected neighbors. This is a common way to represent graphs for traversal algorithms. ```r # Create a sample graph as adjacency list # Graph structure: # 1 # / \ # 2 3 # / \ \ # 4 5 6 graph <- list( "1" = c(2, 3), "2" = c(4, 5), "3" = c(6), "4" = c(), "5" = c(), "6" = c() ) cat("Graph structure (adjacency list):\n") ``` ```r for (vertex in names(graph)) { cat("Vertex", vertex, "-> [", paste(graph[[vertex]], collapse = ", "), "]\n") } ``` -------------------------------- ### Stack Data Structure Operations in R Source: https://context7.com/thealgorithms/r/llms.txt Demonstrates the implementation and usage of a Stack data structure in R, likely using an R6 class. It covers core LIFO operations such as push, pop, peek, checking size, emptiness, and searching for elements. Includes a display method for visualizing the stack content. ```r # Assuming Stack class is defined elsewhere # s <- Stack$new(max_size = 10) # Push operations # s$push("A") # s$push("B") # s$push("C") # s$display() # Stack status # cat("Size:", s$size(), "\n") # 3 # cat("Top:", s$peek(), "\n") # C # cat("Is Empty:", s$is_empty(), "\n") # FALSE # Pop operation # item <- s$pop() # cat("Popped:", item) # s$display() # Search for element (position from top) # s$push("D") # s$push("E") # cat("Position of 'B' from top:", s$search("B")) ``` -------------------------------- ### Evaluate Model Accuracy in R Source: https://github.com/thealgorithms/r/blob/master/documentation/light_gbm.md Calculates the accuracy of the model's predictions by comparing predicted labels to true labels. This snippet assumes `y.test` and `y.pred` are available. The example shows an error because `y.test` is not found. ```r #Test accuracy sum(y.test == (y.pred > 0.5)) / length(y.test) ``` -------------------------------- ### Data Preparation for XGBoost in R Source: https://github.com/thealgorithms/r/blob/master/documentation/xgboost.html This snippet demonstrates how to prepare training and testing data for XGBoost in R. It involves selecting features, converting data to a matrix, and creating an xgb.DMatrix object. Ensure the 'dplyr' and 'xgboost' libraries are installed and loaded. ```r xgboost.train<-xgb.DMatrix(data = select(train.set,-price) %>% as.matrix(),label=train.set$price) xgboost.test<-xgb.DMatrix(data = select(test.set,-price) %>% as.matrix(),label=test.set$price) ``` -------------------------------- ### Train LightGBM Model with RLightGBM in R Source: https://github.com/thealgorithms/r/blob/master/documentation/gradient_boosting_algorithms.md This R snippet illustrates training a LightGBM model using the RLightGBM library. It involves creating data handles, configuring model parameters, training the booster, and making predictions. The code also includes saving the trained model. Dependencies include RLightGBM and example data. ```r # LightGBM library(RLightGBM) data(example.binary) # Parameters num_iterations <- 100 config <- list(objective = "binary", metric="binary_logloss,auc", learning_rate = 0.1, num_leaves = 63, tree_learner = "serial", feature_fraction = 0.8, bagging_freq = 5, bagging_fraction = 0.8, min_data_in_leaf = 50, min_sum_hessian_in_leaf = 5.0) # Create data handle and booster handle.data <- lgbm.data.create(x) lgbm.data.setField(handle.data, "label", y) handle.booster <- lgbm.booster.create(handle.data, lapply(config, as.character)) # Train for num_iterations iterations and eval every 5 steps lgbm.booster.train(handle.booster, num_iterations, 5) # Predict pred <- lgbm.booster.predict(handle.booster, x.test) # Test accuracy sum(y.test == (y.pred > 0.5)) / length(y.test) # Save model (can be loaded again via lgbm.booster.load(filename)) lgbm.booster.save(handle.booster, filename = "/tmp/model.txt") ``` -------------------------------- ### BST Class Definition and Initialization in R Source: https://github.com/thealgorithms/r/blob/master/documentation/binary_search_tree.md Defines the R6 class for a Binary Search Tree (BST) and its initialization method. The constructor sets the root to NULL and size to 0, preparing an empty tree. ```r BST <- R6Class("BST", public = list( root = NULL, size = 0, initialize = function() { self$root <- NULL self$size <- 0 }, # ... other public methods ... ), private = list( # ... private helper methods ... ) ) ``` -------------------------------- ### Perform BFS Traversal on a Complex Graph in R Source: https://github.com/thealgorithms/r/blob/master/documentation/breadth_first_search.html Executes a Breadth-First Search traversal on a complex graph starting from a specified vertex. It returns the order in which vertices are visited. Requires a graph represented as an adjacency list and a starting vertex. ```r complex_graph <- list( "1" = c(2, 3), "2" = c(1, 4, 5), "3" = c(1, 6), "4" = c(2, 7), "5" = c(2, 8), "6" = c(3, 9), "7" = c(4), "8" = c(5), "9" = c(6) ) cat("Complex graph BFS starting from vertex 1:\n") complex_result <- breadth_first_search(complex_graph, 1) cat("Traversal order:", paste(complex_result, collapse = " -> "), "\n") ``` -------------------------------- ### Read Excel File by Sheet Name in R Source: https://github.com/thealgorithms/r/blob/master/documentation/data_processing.html Reads data from an Excel file using the sheet name. This example specifies 'Baltimore Fixed Speed Cameras' as the sheet to read and assumes the first row is a header. An error occurs if the file or function is not found. ```r cameraData <- read.xlsx("./data/cameras.xlsx", "Baltimore Fixed Speed Cameras", header = TRUE) ## Error in read.xlsx("./data/cameras.xlsx", "Baltimore Fixed Speed Cameras", : could not find function "read.xlsx" ``` -------------------------------- ### Read Excel File by Sheet Index in R Source: https://github.com/thealgorithms/r/blob/master/documentation/data_processing.html Reads data from an Excel file into an R data frame. This example uses `read.xlsx` to read the first sheet (sheetIndex = 1) and assumes the first row is a header. An error occurs if the file or function is not found. ```r cameraData <- read.xlsx("./data/cameras.xlsx", sheetIndex = 1, header = TRUE) ## Error in read.xlsx("./data/cameras.xlsx", sheetIndex = 1, header = TRUE): could not find function "read.xlsx" ``` -------------------------------- ### R Linear Search Function and Example Source: https://github.com/thealgorithms/r/blob/master/documentation/linear_search.html Implements a linear search algorithm in R. The `linear_search` function iterates through a vector to find a specific value. If the value is found, it returns the index; otherwise, it returns -1. The example demonstrates calling this function with predefined data and printing the outcome. ```r linear_search<-function(vector, search_value){ #made a function named linear_search having two parameters that are an array and a value to be searched for(i in 1:length(vector)){ if(vector[i]==search_value){ #comparing each value of array with the value to be searched return (i) } } return (-1) } user_vec<- c(10,20,30,40,50,60) #input array (hard code) user_val<-30 #input value to be searched (hard code) result<-linear_search(user_vec,user_val) #linear_seach function calling if(result!=-1){ cat("Searched value", user_val, "found at index", result-1) }else{ cat("Searched value does not exist in array") } ## Searched value 30 found at index 2 ``` -------------------------------- ### Create and Traverse Weighted Graph using Dijkstra's Algorithm in R Source: https://context7.com/thealgorithms/r/llms.txt Demonstrates creating a weighted graph as an adjacency list in R and then applying Dijkstra's algorithm to find the shortest paths from a source vertex. It includes functions to display shortest distances and retrieve the shortest path to a specific vertex. ```r weighted_graph <- list( "1" = list( list(vertex = 2, weight = 4), list(vertex = 3, weight = 2) ), "2" = list( list(vertex = 4, weight = 3) ), "3" = list( list(vertex = 5, weight = 1) ), "4" = list( list(vertex = 5, weight = 2) ), "5" = list() ) # Assuming dijkstra_shortest_path and get_shortest_path are defined elsewhere # result <- dijkstra_shortest_path(weighted_graph, 1) # cat("Shortest distances from vertex 1:\n") # for (i in 1:length(result$distances)) { # if (result$distances[i] != Inf) { # cat("To vertex", i, ": distance =", result$distances[i], "\n") # } # } # path_to_5 <- get_shortest_path(result, 1, 5) # cat("Path:", paste(path_to_5$path, collapse = " -> ")) ``` -------------------------------- ### Binary Search Tree Class Initialization and Core Operations in R Source: https://github.com/thealgorithms/r/blob/master/documentation/binary_search_tree.html Implements the main Binary Search Tree class using R6. It includes initialization, insertion, searching, and deletion methods. The `insert` method handles new node placement, and `search` checks for value existence. `delete` removes a node while maintaining BST properties. ```r # Binary Search Tree class BST <- R6Class("BST", public = list( root = NULL, size = 0, initialize = function() { self$root <- NULL self$size <- 0 }, # Insert a value into the BST insert = function(value) { if (is.null(self$root)) { self$root <- BSTNode$new(value) self$size <- self$size + 1 } else { private$insert_recursive(self$root, value) } }, # Search for a value in the BST search = function(value) { return(private$search_recursive(self$root, value)) }, # Delete a value from the BST delete = function(value) { if (self$search(value)) { self$root <- private$delete_recursive(self$root, value) self$size <- self$size - 1 return(TRUE) } return(FALSE) }, # Find minimum value in the BST find_min = function() { if (is.null(self$root)) return(NULL) return(private$find_min_recursive(self$root)$value) }, # Find maximum value in the BST find_max = function() { if (is.null(self$root)) return(NULL) return(private$find_max_recursive(self$root)$value) }, # In-order traversal (left, root, right) - gives sorted output inorder_traversal = function() { result <- c() private$inorder_recursive(self$root, result) return(result) }, # Pre-order traversal (root, left, right) preorder_traversal = function() { result <- c() private$preorder_recursive(self$root, result) return(result) }, # Post-order traversal (left, right, root) postorder_traversal = function() { result <- c() private$postorder_recursive(self$root, result) return(result) }, # Level-order traversal (breadth-first) level_order_traversal = function() { if (is.null(self$root)) return(c()) result <- c() queue <- list(self$root) while (length(queue) > 0) { node <- queue[[1]] queue <- queue[-1] result <- c(result, node$value) if (!is.null(node$left)) { queue <- append(queue, list(node$left)) } if (!is.null(node$right)) { queue <- append(queue, list(node$right)) } } return(result) }, # Get height of the tree height = function() { return(private$height_recursive(self$root)) }, # Check if tree is valid BST is_valid_bst = function() { return(private$is_valid_bst_recursive(self$root, -Inf, Inf)) }, # Get size of the tree get_size = function() { return(self$size) }, # Check if tree is empty is_empty = function() { return(is.null(self$root)) }, # Print tree structure print_tree = function() { if (is.null(self$root)) { cat("Empty tree\n") return() } private$print_tree_recursive(self$root, "", TRUE) } ), private = list( # Recursive helper for insertion insert_recursive = function(node, value) { if (value < node$value) { if (is.null(node$left)) { node$left <- BSTNode$new(value) self$size <- self$size + 1 } else { private$insert_recursive(node$left, value) } } else if (value > node$value) { if (is.null(node$right)) { node$right <- BSTNode$new(value) self$size <- self$size + 1 } else { private$insert_recursive(node$right, value) } } # If value == node$value, don't insert (no duplicates) }, # Recursive helper for search search_recursive = function(node, value) { if (is.null(node) || node$value == value) { return(!is.null(node)) } if (value < node$value) { return(private$search_recursive(node$left, value)) } else { return(private$search_recursive(node$right, value)) } }, # Recursive helper for deletion delete_recursive = function(node, value) { if (is.null(node)) { return(NULL) } ``` -------------------------------- ### Example Usage of OLS Function in R Source: https://github.com/thealgorithms/r/blob/master/documentation/linearregressionrawr.html This R code snippet demonstrates how to use the custom `ols` function. It first sets a random seed for reproducibility, generates a synthetic response variable `y` and a predictor variable `x`, and then calls the `ols` function with `y` and `x`. The example also includes a comment indicating a potential error that might occur. ```R set.seed(1) x <- rnorm(1000) y <- 4 * x + rnorm(1000, sd = .5) olds(y=y,x=matrix(x, ncol = 1)) ## Error in terms.formula(object, data = data): '.' in formula and no 'data' argument ``` -------------------------------- ### Fibonacci Sequence in R Source: https://context7.com/thealgorithms/r/llms.txt A recursive function to calculate the nth number in the Fibonacci sequence. Includes examples of calculating individual terms and generating a sequence. ```r Fibonacci <- function(n) { if (n == 1 | n == 2) { return(1) } else { return(Fibonacci(n - 1) + Fibonacci(n - 2)) } } # Usage Fibonacci(1) # 1 Fibonacci(10) # 55 Fibonacci(15) # 610 # Generate sequence sapply(1:10, Fibonacci) # [1] 1 1 2 3 5 8 13 21 34 55 ``` -------------------------------- ### Train LightGBM Model with RLightGBM in R Source: https://github.com/thealgorithms/r/blob/master/documentation/gradient_boosting_algorithms.html This R snippet illustrates how to train a LightGBM model using the RLightGBM library. It involves creating a data handle, setting the label field, configuring parameters such as objective and learning rate, and then creating and training the booster. ```r library(RLightGBM) data(example.binary) # Parameters num_iterations <- 100 config <- list(objective = "binary", metric="binary_logloss,auc", learning_rate = 0.1, num_leaves = 63, tree_learner = "serial", feature_fraction = 0.8, bagging_freq = 5, bagging_fraction = 0.8, min_data_in_leaf = 50, min_sum_hessian_in_leaf = 5.0) # Create data handle and booster handle.data <- lgbm.data.create(x) lgbm.data.setField(handle.data, "label", y) handle.booster <- lgbm.booster.create(handle.data, lapply(config, as.character)) # Train for num_iterations iterations and eval every 5 steps ``` -------------------------------- ### Load DBSCAN Package in R Source: https://github.com/thealgorithms/r/blob/master/documentation/dbscan_clustering.md Attempts to load the 'dbscan' package in R. This is a prerequisite for using DBSCAN functions. An error indicates the package is not installed. ```r library(dbscan) ``` -------------------------------- ### Initialize BST and Insert Grades in R Source: https://github.com/thealgorithms/r/blob/master/documentation/binary_search_tree.md Initializes an empty Binary Search Tree (BST) and inserts a list of student grades into it. The BST is assumed to be implemented by a 'BST' class with an 'insert' method. This sets up the data structure for subsequent operations. ```r grade_bst <- BST$new() grades <- c(85, 92, 78, 96, 83, 88, 91, 79, 87, 94) cat("Student grades:", paste(grades, collapse = ", "), "\n") for (grade in grades) { grade_bst$insert(grade) } ``` -------------------------------- ### Fit KNN Model in R Source: https://github.com/thealgorithms/r/blob/master/documentation/knn.html This snippet shows the core KNN model fitting process in R using the knn function. It specifies the formula, the training data, and the value of k. The error 'could not find function "knn"' is likely due to the 'knn' package not being loaded successfully. ```r # Fitting model fit <-knn(y_train ~ ., data = x,k=5) ## Error in knn(y_train ~ ., data = x, k = 5): could not find function "knn" ``` -------------------------------- ### R BST: In-order, Pre-order, Post-order, and Level-order Traversals Source: https://github.com/thealgorithms/r/blob/master/documentation/binary_search_tree.html This snippet shows different ways to traverse a Binary Search Tree: in-order (sorted), pre-order, post-order, and level-order (BFS). It assumes corresponding traversal methods exist on the BST object. ```R cat("In-order (sorted): ", paste(bst$inorder_traversal(), collapse = ", "), "\n") cat("Pre-order: ", paste(bst$preorder_traversal(), collapse = ", "), "\n") cat("Post-order: ", paste(bst$postorder_traversal(), collapse = ", "), "\n") cat("Level-order (BFS): ", paste(bst$level_order_traversal(), collapse = ", "), "\n\n") ```