计算包含R中给定值或术语的文件数

时间:2012-11-12 16:42:59

标签: r

我有一个包含一组不同数据文件的文件夹。我想计算包含给定术语的文件数量,如“25”或“颜色编码”,如果可能,列出这些文件的名称。他们在R中有没有办法做到这一点?

1 个答案:

答案 0 :(得分:1)

这是否符合您的需要

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)
}

示例:

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

findTermsInFileNames(terms, fold)