Skip to content

Commit

Permalink
added pks to googlesheet reads
Browse files Browse the repository at this point in the history
  • Loading branch information
collinschwantes committed Jun 17, 2024
1 parent 903d2fd commit 0d7be21
Showing 1 changed file with 30 additions and 7 deletions.
37 changes: 30 additions & 7 deletions R/read_googlesheets.R
Original file line number Diff line number Diff line change
Expand Up @@ -6,19 +6,23 @@
#' @param sheet Sheet to read, in the sense of "worksheet" or "tab".
#' @param ss Something that identifies a Google Sheet such as drive id or URL
#' @param ... other arguments passed to `googlesheets4::range_read()`
#' @param add_primary_key_field Logical. Should a primary key field be added?
#' @param primary_key character. The column name for the unique identifier to be added to the data.
#'
#' @return tibble
#' @export
#' @seealso [googlesheets4::range_read()]
#' @examples
#' \dontrun{
#' read_googlesheets(ss = kzn_animal_ship_sheets, sheet = "all")
#' read_googlesheets(ss = kzn_animal_ship_sheets, sheet = "all",)
#' }
#'
read_googlesheets <-
function(key_path,
sheet = "all",
ss,
add_primary_key_field = FALSE,
primary_key = "primary_key",
...) {
# Handle authentication
googledrive::drive_auth(path = key_path)
Expand All @@ -30,12 +34,23 @@ read_googlesheets <-
sheet_names <- rlang::set_names(sheet_names, sheet_names)
dat <-
purrr::map(sheet_names,
\(x) googlesheets4::range_read(
ss = ss,
sheet = x,
na = c("", "NA", "NULL", "-"),
...
))
\(x){
df <- googlesheets4::range_read(
ss = ss,
sheet = x,
na = c("", "NA", "NULL", "-"),
...
)

if(add_primary_key_field){
#ss_sheet_rownum

row_ids <- paste(ss,x,1:nrow(df),sep = "_")
df <- df %>%
dplyr::mutate({{primary_key}} := {{row_ids}})
}
return(df)
} )

} else{
dat <-
Expand All @@ -46,6 +61,14 @@ read_googlesheets <-
...
)

if(add_primary_key_field){
#ss_sheet_rownum
row_ids <- paste(ss,x,1:nrow(dat),sep = "_")

dat <- dat %>%
dplyr::mutate({{primary_key}} := {{row_ids}})
}

}

return(dat)
Expand Down

0 comments on commit 0d7be21

Please sign in to comment.