Skip to content

Commit f01638a

Browse files
committed
refactored function read_keyvalue
1 parent e3c35ce commit f01638a

File tree

1 file changed

+12
-12
lines changed

1 file changed

+12
-12
lines changed

R/read.R

Lines changed: 12 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -43,32 +43,32 @@ read_cells <- function(drfile, sheet, variables, translate = FALSE, translations
4343
#' @noRd
4444
#'
4545
read_keyvalue <- function(drfile, sheet, ranges, translate = FALSE, translations = NULL, atomicclass = "character", ...) {
46-
46+
# Read and combine key-value pairs from the specified ranges
4747
kvtable <- lapply(ranges, function(range) {
4848
readxl::read_excel(drfile, sheet = sheet, range = range, col_names = c("key", "value"))
49-
}) |>
50-
dplyr::bind_rows()
49+
}) |> dplyr::bind_rows()
5150

51+
# Translate keys if required
5252
if (translate) {
5353
kvtable$key <- long_to_shortnames(kvtable$key, translations)
5454
}
5555

56+
# Convert values to a list
5657
kvlist <- as.list(kvtable$value)
5758

58-
if (length(atomicclass) == 1) {
59-
kvlist <- lapply(kvlist, coerce, atomicclass)
59+
# Coerce values to the specified atomic class
60+
kvlist <- if (length(atomicclass) == 1) {
61+
lapply(kvlist, coerce, atomicclass)
6062
} else {
6163
if (length(atomicclass) != length(kvlist)) {
62-
rlang::abort(
63-
glue::glue("The number of atomic classes ({ length(atomicclass) }) must be 1 or equal to the
64-
number of elements ({ length(kvlist) }) in the keyvalue table.")
65-
)
64+
rlang::abort(glue::glue(
65+
"The number of atomic classes ({length(atomicclass)}) must be 1 or equal to the number of elements ({length(kvlist)}) in the key-value table."
66+
))
6667
}
67-
kvlist <- lapply(seq_along(kvlist), function(i) {
68-
kvlist[[i]] |> coerce(atomicclass[i])
69-
})
68+
mapply(coerce, kvlist, atomicclass, SIMPLIFY = FALSE)
7069
}
7170

71+
# Return a named list with keys and coerced values
7272
setNames(kvlist, kvtable$key)
7373
}
7474

0 commit comments

Comments
 (0)