R/importR.R

Defines functions import

Documented in import

#'@title Import a dataset
#'
#'@description
#'The import function can import data from delimited text files,
#'EXCEL spreadsheets, and statistical packages such as SAS, SPSS, and Stata.
#'
#'@param file datafile to import. If missing, the user
#'is prompted to select a file interactively.
#'@param ... parameters passed to the import function. See details below.
#'
#'@return a data frame
#'
#'@details
#'The \code{import} function is a wrapper for the
#'\href{https://haven.tidyverse.org/}{haven},
#'\href{https://readxl.tidyverse.org/}{readxl},
#'and \href{https://github.com/r-lib/vroom}{vroom}
#'packages.
#'
#'@seealso
#'\link[haven]{read_sas},
#'\link[haven]{read_dta},
#'\link[haven]{read_spss},
#'\link[readxl]{read_excel},
#'\link[vroom]{vroom}
#'
#'
#'@export
#'
#'@importFrom haven read_sas read_spss read_stata
#'@importFrom readxl read_excel
#'@import vroom
#'@importFrom tools file_ext
#'
#'@examples
#' \dontrun{
#' #import comma delimited file
#' mydataframe <- import("mydata.csv")
#'
#' # import SAS binary data file
#' mydataframe <- import("mydata.sas7bdat")
#'
#' # import the second sheet of an EXCEL workbook
#' mydataframe <- import("mydata.xlsx", sheet = 2)
#'
#' # prompt for a file to import
#' mydataframe <- import()
#' }


import <- function(file, ...){

  # if no file specified, prompt user

  if(missing(file))
    file <- file.choose()


  # get file info

  file <- tolower(file)
  basename <- basename(file)
  extension <- tools::file_ext(file)


  # import dataset

  df <- switch(extension,
               "sas7bdat" = haven::read_sas(file, ...),
               "dta" = haven::read_stata(file, ...),
               "sav" = haven::read_spss(file, ...),
               "xlsx" = readxl::read_excel(file, ...),
               "xls" = readxl::read_excel(file, ...),
               vroom::vroom(file, ...)
  )

  # return data frame
  return(df)

}
prekshasreewastav/ImportR documentation built on Dec. 22, 2021, 9:51 a.m.