# safe_read_csv.R
#' @include internals.R
#' @rdname safe_read_csv
#' @template safe_read_csv
#' @export
safe_read_csv <- function(x, ...)
{
if (length(x) > 1L || !is.character(x)) {
stop("'x' must be a character of length 1.",
call. = FALSE)
}
if (!utils::file_test("-f", x)) {
stop("'x' points to a file that does not exist.",
call. = FALSE)
}
if (!identical(.file_ext(basename(x)), "csv")) {
stop("'x' does not point to a CSV (Comma Separated Value) file.",
call. = FALSE)
}
if (!isOpen(con <- file(x, "rb"), rw = "read")) {
stop("a connection error occured.", call. = FALSE)
} else {
close(con)
}
tryCatch(
{
return(do.call(data.table::fread, safe_read_ops(file = x, ...)))
},
error = function(cond) {
stop(conditionMessage(cond), call. = FALSE)
},
warning = function(cond) {
stop(conditionMessage(cond), call. = FALSE)
}
)
}
#' @rdname safe_read_csv
#' @export
safe_read_ops <- function(...)
{
default_params <- list(
na.strings = ",,",
sep = "auto",
sep2 = "auto",
dec = ".",
quote = "\"",
nrows = Inf,
header = TRUE,
verbose = FALSE,
integer64 = "character",
encoding = "unknown",
fill = FALSE,
showProgress = FALSE,
data.table = TRUE,
logical01 = FALSE
)
if (...length()) {
user_params <- list(...)
default_params[names(user_params)] <- user_params
}
return(default_params)
}
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.