jumpingrivers / datasauRus

R Package 📦 Containing the Datasaurus Dozen datasets :bar_chart:
https://jumpingrivers.github.io/datasauRus
Other
319 stars 47 forks source link

Feature: CSV export #40

Open StatsRhian opened 2 years ago

StatsRhian commented 2 years ago

It could be nice to have the ability to export a CSV of the datasaurus data from the R package itself

cyberLaVoy commented 1 year ago

Here is a possible solution to this issue.

#' Save Datasets from an R Package
#'
#' The save_datasets function saves all datasets in a specified R package, saving them as CSV files in a specified folder.
#'
#' @param package_name The name of the R package containing the datasets to be saved. The default value is "datasauRus".
#' @param folder_name The name of the folder where the CSV files will be saved. The default value is "datasaurus_dozen_datasets".
#'
#' @return The save_datasets function doesn't return anything.
#' @export
save_datasets <- function(package_name="datasauRus", folder_name="datasaurus_dozen_datasets") {
  # Get a list of all datasets in the package
  datasets <- data(package = package_name)

  # Create the specified folder in the current working directory, if it doesn't already exist
  if (!dir.exists(folder_name)) {
    dir.create(folder_name)
  }

  # Loop through each dataset
  for ( dataset in datasets$results[, "Item"] )  {
    # Write the dataset to a csv file in the specified folder
    write.csv(get(dataset), file = paste0(folder_name, "/", dataset, ".csv"))
  }
}

This function is package ready, with all documentation. Note that we are able to set default arguments for package_name and folder_name because this function would be apart of this package. And therefore would be contextually correct.

Next iteration on this function could provide an option to save the datasets in different formats, such as in Excel and/or RDA format.