forked from tidyverse/dplyr
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsrc-local.r
62 lines (56 loc) · 1.65 KB
/
src-local.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
59
60
61
62
#' A local source.
#'
#' This is mainly useful for testing, since makes it possible to refer to
#' local and remote tables using exactly the same syntax.
#'
#' Generally, \code{src_local} should not be called directly, but instead
#' one of the constructors should be used.
#'
#' @param tbl name of the function used to generate \code{tbl} objects
#' @param pkg,env Either the name of a package or an environment object in
#' which to look for objects.
#' @keywords internal
#' @export
#' @examples
#' if (require("Lahman")) {
#' batting_df <- tbl(src_df("Lahman"), "Batting")
#' }
src_local <- function(tbl, pkg = NULL, env = NULL) {
if (!xor(is.null(pkg), is.null(env))) {
stop("Must supply exactly one of pkg and env", call. = FALSE)
}
if (!is.null(pkg)) {
env <- getNamespaceInfo(pkg, "lazydata")
name <- paste0("<package: ", pkg, ">")
} else {
name <- utils::capture.output(print(env))
}
structure(
list(tbl_f = match.fun(tbl), name = name, env = env),
class = c("src_local", "src")
)
}
#' @rdname src_local
#' @export
src_df <- function(pkg = NULL, env = NULL) {
src_local("tbl_df", pkg, env)
}
#' @export
src_tbls.src_local <- function(x, ...) {
objs <- ls(envir = x$env)
Filter(function(obj) is.data.frame(get(obj, envir = x$env)), objs)
}
#' @export
tbl.src_local <- function(src, from, ...) {
src$tbl_f(get(from, src$env))
}
#' @export
copy_to.src_local <- function(dest, df, name = deparse(substitute(df)), ...) {
assign(name, envir = dest$env, df)
tbl(dest, name)
}
#' @export
format.src_local <- function(x, ...) {
paste0("src: ", x$name, "\n",
wrap("tbls: ", paste0(sort(src_tbls(x)), collapse = ", ")))
}