|
| 1 | +#' Find variables and their paths in a Crunch dataset or folder |
| 2 | +#' |
| 3 | +#' @param x Crunch dataset or variable folder |
| 4 | +#' @param deep FALSE (the default) or TRUE; should subfolders |
| 5 | +#' @param include.hidden FALSE (default) or TRUE, should hidden be included in the result? |
| 6 | +#' |
| 7 | +#' @return Data.frame with one row per Crunch variable and columns \code{alias}, \code{path}, \code{hidden} |
| 8 | +#' @export |
| 9 | +findVariables <- function(x, deep = FALSE, include.hidden = FALSE) { |
| 10 | + if (is.dataset(x)) { |
| 11 | + x <- cd(x, ".") |
| 12 | + startpath <- "" |
| 13 | + } else if (is.folder(x)) { |
| 14 | + startpath <- name(x) |
| 15 | + } else { |
| 16 | + halt('`x` should be "CrunchDataset" or "VariableFolder", not "', paste(class(x), collapse = ", "), '"') |
| 17 | + } |
| 18 | + if (!isTRUE(deep) && !isFALSE(deep)) { |
| 19 | + halt("`deep` should be TRUE or FALSE") |
| 20 | + } |
| 21 | + if (!isTRUE(include.hidden) && !isFALSE(include.hidden)) { |
| 22 | + halt("`hidden` should be TRUE or FALSE") |
| 23 | + } |
| 24 | + if (!deep) { |
| 25 | + vars <- aliases(variables(x)) |
| 26 | + nvars <- length(vars) |
| 27 | + res <- data.frame(alias = vars, path = rep(startpath, nvars), hidden = rep(FALSE, nvars)) |
| 28 | + return(res) |
| 29 | + } |
| 30 | + res <- .findVariables(x, startpath) |
| 31 | + res$hidden <- rep(FALSE, nrow(res)) |
| 32 | + if (include.hidden) { |
| 33 | + hidden <- .findVariables(hiddenFolder(x), startpath) |
| 34 | + hidden$hidden <- rep(TRUE, nrow(hidden)) |
| 35 | + res <- rbind(res, hidden) |
| 36 | + } |
| 37 | + res |
| 38 | +} |
| 39 | + |
| 40 | +.findVariables <- function(x, path) { |
| 41 | + vars <- variables(x) |
| 42 | + res <- data.frame(alias = aliases(vars), path = rep(path, length(vars))) |
| 43 | + dirs <- x[types(x) %in% "folder"] |
| 44 | + if (length(dirs) == 0) { |
| 45 | + return(res) |
| 46 | + } |
| 47 | + dirnames <- names(dirs) |
| 48 | + res2 <- lapply(seq_along(dirnames), function(i) { |
| 49 | + if (identical(path, "")) { |
| 50 | + new_path <- dirnames[i] |
| 51 | + } else { |
| 52 | + new_path <- paste(path, dirnames[i], sep = " | ") |
| 53 | + } |
| 54 | + .findVariables(dirs[[i]], new_path) |
| 55 | + }) |
| 56 | + rbind(res, do.call(rbind, res2)) |
| 57 | +} |
0 commit comments