Skip to content

Commit

Permalink
add read_excel
Browse files Browse the repository at this point in the history
  • Loading branch information
kongdd committed Dec 23, 2024
1 parent acf7b1b commit b19e79c
Show file tree
Hide file tree
Showing 4 changed files with 56 additions and 27 deletions.
1 change: 1 addition & 0 deletions NAMESPACE
Original file line number Diff line number Diff line change
Expand Up @@ -153,6 +153,7 @@ export(print2)
export(pro_map)
export(progressively)
export(quantile_envelope)
export(read_excel)
export(read_ufile)
export(read_xlsx)
export(read_xlsx2list)
Expand Down
27 changes: 0 additions & 27 deletions R/tools_data.table.R
Original file line number Diff line number Diff line change
Expand Up @@ -18,30 +18,3 @@ fread_dir <- function(indir, pattern = "*.csv", ..., .progress="text", list2df=T
res
})
}

#' @export
read_ufile <- function(f, nodata = c(-99999, -9999)) {
unit <- fread(f, nrows = 1)
dat <- fread(f, skip = 2, header = FALSE)
for (nd in nodata) {
dat[dat == nd] <- NA
}
names(dat) <- names(unit)
structure(list(data = dat, unit = unit), class = "unit_df")
}

# define a S3 method
#' @export
write_ufile <- function(x, ...) UseMethod("write_ufile")

#' @export
write_ufile.data.frame <- function(data, unit, fout) {
fwrite(unit, fout)
fwrite(data, fout, col.names = FALSE, append = TRUE)
}

#' @export
write_ufile.unit_df <- function(l, fout) {
fwrite(l$unit, fout)
fwrite(l$data, fout, col.names = FALSE, append = TRUE)
}
41 changes: 41 additions & 0 deletions R/tools_ufile.R
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
#' @export
read_ufile <- function(f, nodata = c(-99999, -9999)) {
unit <- fread(f, nrows = 1)
dat <- fread(f, skip = 2, header = FALSE)
for (nd in nodata) {
dat[dat == nd] <- NA
}
names(dat) <- names(unit)
structure(list(data = dat, unit = unit), class = "unit_df")
}

# define a S3 method
#' @export
write_ufile <- function(x, ...) UseMethod("write_ufile")

#' @export
write_ufile.data.frame <- function(data, unit, fout) {
fwrite(unit, fout)
fwrite(data, fout, col.names = FALSE, append = TRUE)
}

#' @export
write_ufile.unit_df <- function(l, fout) {
fwrite(l$unit, fout)
fwrite(l$data, fout, col.names = FALSE, append = TRUE)
}

#' read csv or xls/xlsx file
#'
#' @param ... others to fun, one of [data.table::fread()], [readxl::read_xls()], [read_xlsx()]
#' @export
read_excel <- function(f, ...) {
fun <- switch(file_ext(f),
csv = data.table::fread,
xls = readxl::read_xls,
xlsx = read_xlsx
)
d <- fun(f, ...)
if ("DOY" %in% names(d)) d <- dplyr::select(d, -DOY)
d |> data.table()
}
14 changes: 14 additions & 0 deletions man/read_excel.Rd

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

0 comments on commit b19e79c

Please sign in to comment.