apexcharter/R/parse-data.R

50 lines
1.3 KiB
R
Raw Normal View History

2018-09-03 23:52:53 +02:00
#' @title Convert a \code{data.frame} to a \code{list}
#'
#' @description Convert data to a format suitable for ApexCharts.js
#'
#' @param data A \code{data.frame} or an object coercible to \code{data.frame}.
2018-12-18 18:02:09 +01:00
#' @param add_names Use names of columns in output. Can be logical to
#' reuse \code{data} names or a character vector of new names.
2018-09-03 23:52:53 +02:00
#'
#' @export
2018-12-18 18:02:09 +01:00
#' @importFrom stats setNames
2018-09-03 23:52:53 +02:00
#'
2018-12-18 18:02:09 +01:00
parse_df <- function(data, add_names = FALSE) {
2018-09-03 23:52:53 +02:00
data <- as.data.frame(data)
2018-12-18 18:02:09 +01:00
names_ <- names(data)
2018-09-03 23:52:53 +02:00
l <- lapply(
X = data[],
FUN = function(x) {
2019-02-14 15:50:58 +01:00
if (inherits(x, "Date") & identical(add_names, FALSE)) {
as.numeric(x) * 86400000
2019-02-15 23:06:11 +01:00
} else if (inherits(x, "POSIXt")) {
as.numeric(x) * 1000
2018-09-03 23:52:53 +02:00
} else if (inherits(x, "factor")) {
as.character(x)
} else {
2019-02-14 17:40:03 +01:00
# if (!identical(add_names, FALSE)) {
# formatNoSci(x)
# } else {
# x
# }
x
2018-09-03 23:52:53 +02:00
}
}
)
2019-02-14 15:50:58 +01:00
ll <- lapply(
X = seq_len(nrow(data)),
FUN = function(i) {
res <- lapply(l, `[[`, i)
if (identical(add_names, FALSE)) {
res <- unname(res)
}
if (is.character(add_names) & length(add_names) == length(names_)) {
res <- setNames(res, nm = add_names)
}
return(res)
}
)
2018-12-18 18:02:09 +01:00
return(ll)
2018-09-03 23:52:53 +02:00
}