[R] list.dirs() full.names broken?

J Toll jctoll at gmail.com
Sat Apr 14 02:37:58 CEST 2012


OK, well list.dirs() seems broken to me.  In case someone else needs a
working version, I wrote a new function called lsdir().  It adds the
ability to choose whether to include hidden directories.  It should
work on Mac and probably Linux/Unix.

lsdir <- function(path, format = "relative", recursive = FALSE, all = FALSE) {
  # list directories
  # format is any part of "fullpath", "relative", or "basename"

  # set a path if necessary
  if (missing(path)) {
    path <- "."
  }

  # recursion
  if (recursive == FALSE) {
    argRecursive <- "-maxdepth 1"
  } else if (recursive) {
    argRecursive <- ""
  }

  # piece together system command
  execFind <- paste("find", path, "-type d", argRecursive,
                    "-mindepth 1 -print", sep = " ")

  # execute system command
  tmp <- system(execFind, intern = TRUE)

  # remove .hidden files if all == FALSE
  if (all == FALSE) {
    tmp <- tmp[grep("^\\..*", basename(tmp), invert = TRUE)]
  }

  # match format argument
  format <- match.arg(tolower(format), c("fullpath", "relative", "basename"))

  # format output based upon format argument
  if (format == "basename") {
    out <- basename(tmp)
  } else if (format == "fullpath") {
    out <- normalizePath(tmp)
  } else {
    out <- tmp
  }

  # clean up any duplicate "/" and return
  return(gsub("/+", "/", out))

}


James



More information about the R-help mailing list