user785099
user785099

Reputation: 5563

counting the number of files containing a given value or term in R

I have a folder holding a set of different data files. I would like to count the number of files that contain a given term, like "25" or "color coding", and if possible, listing the name of those files. Are they any ways to do that in R?

Upvotes: 1

Views: 1324

Answers (1)

Ricardo Saporta
Ricardo Saporta

Reputation: 55390

Does this do what you need

findTermsInFileNames <- function(terms, theFolder="path/to/Folder/", extension="R", ignoreCase=TRUE)  {
  # Iterates through all files of type `extension` in `theFolder` and returns a 
  #  count for each time one of `terms` appears in a file name
  # Note:  extension should NOT include a dot.  good: "*"  bad: ".*"

  # str_detect is from stringr
  require(stringr)

  # Get list of files
  pat <- paste0("*.", extension)
  filesList <- list.files(path.expand(theFolder), pattern=pat, ignore.case=ignoreCase)

  # Add attribute to terms, whether cAseS should be ignored
  attr(terms, "ignore.case") <- ignoreCase

  # Tabulate all occurrences of temrs in the list of file names
  results <- rowSums(sapply(filesList,  str_detect, terms, USE.NAMES=TRUE)) 

  # Clean up the table names
  names(results) <- terms

  return(results)
}

Example:

fold <- "~/git/src"
terms <- c("an", "example", "25")

findTermsInFileNames(terms, fold)

Upvotes: 1

Related Questions