【问题标题】:R function that selects 2 files with the similar file namesR函数选择2个具有相似文件名的文件
【发布时间】:2020-02-21 03:14:39
【问题描述】:

我正在尝试匹配具有相似文件名的文件以用作函数的输入。例如, 如果目录中的文件名是:

atac.macaque.R1.fastq.gz
atac.macaque.R2.fastq.gz
atac.human.R1.fastq.gz
atac.human.R2.fastq.gz 

是否有一个函数可以识别 atac.macaque.R1.fastq.gz 和 atac.macaque.R2.fastq.gz 是对的并且应该分别作为 x 和 y 输入到将读取这些文件的函数中?

我希望找到一个函数,它可以遍历目录中的所有文件对(它们都以不同的名称开头,即 atac.human 与 atac.macaque),然后应用于我使用的文件读取函数.

【问题讨论】:

  • 或许使用正则表达式来选择合适的匹配?

标签: r


【解决方案1】:

每个文件都有一对吗?如果是,那么你可以得到文件路径的向量,并在对名称进行排序后将它们放入一个矩阵中。

x <- sort(list.files('/path/to/directory', pattern = "\\.gz$"))
mat <- matrix(x, ncol = 2)
mat

#     [,1]                     [,2]                      
#[1,] "atac.human.R1.fastq.gz" "atac.macaque.R1.fastq.gz"
#[2,] "atac.human.R2.fastq.gz" "atac.macaque.R2.fastq.gz"

现在,每一列都是一对,如果你有一些函数将这两个文件作为参数,你可以使用apply column-wise 将这些函数应用于每一对。

some_func <- function(x, y) #does some thing with x & y
apply(mat, 2, some_func)

【讨论】:

  • x &lt;- sort(list.files('/path/to/directory', pattern = "\\.gz$")) ...这将是完美的!
  • 是的,这可能更安全。谢谢,更新了答案。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-09-24
  • 2018-01-14
  • 1970-01-01
  • 1970-01-01
  • 2010-11-07
  • 1970-01-01
  • 2020-02-07
相关资源
最近更新 更多