-
Notifications
You must be signed in to change notification settings - Fork 65
/
Copy pathas_data.R
58 lines (55 loc) · 1.8 KB
/
as_data.R
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
#' @name as_data
#' @title convert other objects to greta arrays
#' @description define an object in an R session as a data greta array for use
#' as data in a greta model.
#' @param x an R object that can be coerced to a greta_array (see details).
#' @details \code{as_data()} can currently convert R objects to greta_arrays if
#' they are numeric or logical vectors, matrices or arrays; or if they are
#' dataframes with only numeric (including integer) or logical elements.
#' Logical elements are always converted to numerics. R objects cannot be
#' converted if they contain missing (\code{NA}) or infinite (\code{-Inf} or
#' \code{Inf}) values.
#' @export
#' @examples
#' \dontrun{
#'
#' # numeric/integer/logical vectors, matrices and arrays can all be coerced to
#' # data greta arrays
#'
#' vec <- rnorm(10)
#' mat <- matrix(seq_len(3 * 4), nrow = 3)
#' arr <- array(sample(c(TRUE, FALSE), 2 * 2 * 2, replace = TRUE),
#' dim = c(2, 2, 2))
#' (a <- as_data(vec))
#' (b <- as_data(mat))
#' (c <- as_data(arr))
#'
#' # dataframes can also be coerced, provided all the columns are numeric,
#' # integer or logical
#' df <- data.frame(x1 = rnorm(10),
#' x2 = sample(1L:10L),
#' x3 = sample(c(TRUE, FALSE), 10, replace = TRUE))
#' (d <- as_data(df))
#' }
as_data <- function(x) {
check_tf_version("error")
UseMethod("as_data", x)
}
# if it's already a *data* greta_array fine, else error
# Begin Exclude Linting
#' @export
as_data.greta_array <- function(x) {
# End Exclude Linting
if (!inherits(get_node(x), "data_node")) {
stop("cannot coerce a non-data greta_array to data",
call. = FALSE)
}
x
}
# otherwise try to coerce to a greta array
# Begin Exclude Linting
#' @export
as_data.default <- function(x) {
# End Exclude Linting
as.greta_array(x)
}