循环浏览R中的.dat文件并仅提取特定数据作为列

时间:2018-07-11 16:08:12

标签: python r loops extraction

我的本​​地驱动器中有900多个文件夹,每个文件夹都有一个.dat扩展名文件。我想遍历每个文件夹以访问其中的文件,以仅获取特定数据并将该数据写入新文件中。每个.dat文件看起来都像这样-

Authors:
#    Pallavi Subhraveti
#    Quang Ong
#    Tim Holland
#    Anamika Kothari
#    Ingrid Keseler 
#    Ron Caspi
#    Peter D Karp

# Please see the license agreement regarding the use of and distribution of 
this file.
# The format of this file is defined at http://bioinformatics.ai.sri.com
# Version: 21.5
# File Name: compounds.dat
# Date and time generated: October 24, 2017, 14:52:45

# Attributes:
#    UNIQUE-ID
#    TYPES
#    COMMON-NAME
#    ABBREV-NAME
#    ACCESSION-1
#    ANTICODON
#    ATOM-CHARGES
#    ATOM-ISOTOPES
#    CATALYZES
#    CFG-ICON-COLOR
#    CHEMICAL-FORMULA
#    CITATIONS
#    CODONS
#    COFACTORS-OF
#    MOLECULAR-WEIGHT
#    MONOISOTOPIC-MW

[Data Chunk 1]
UNIQUE-ID - CPD0-1108
TYPES - D-Ribofuranose
COMMON-NAME - β-D-ribofuranose
ATOM-CHARGES - (9 -1)
ATOM-CHARGES - (6 1)
CHEMICAL-FORMULA - (C 5)
CHEMICAL-FORMULA - (H 14)
CHEMICAL-FORMULA - (N 1)
CHEMICAL-FORMULA - (O 6)
CHEMICAL-FORMULA - (P 1)
CREDITS - SRI
CREDITS - kaipa
DBLINKS - (CHEBI "10647" NIL |kothari| 3594051403 NIL NIL)
DBLINKS - (BIGG "37147" NIL |kothari| 3584718837 NIL NIL)
DBLINKS - (PUBCHEM "25200464" NIL |taltman| 3466375284 NIL NIL)
DBLINKS - (LIGAND-CPD "C01233" NIL |keseler| 3342798255 NIL NIL)
INCHI - InChI=1S/C5H14NO6P/c6-1-2-11-13(9,10)12-4-5(8)3-7/h5,7-8H,1-4,6H2,(H,9,10)
MOLECULAR-WEIGHT - 215.142    
MONOISOTOPIC-MW - 216.0636987293    
NON-STANDARD-INCHI - InChI=1S/C5H14NO6P/c6-1-2-11-13(9,10)12-4-5(8)3-7/h5,7-8H,1-4,6H2,(H,9,10)
SMILES - C(OP([O-])(OCC(CO)O)=O)C[N+]
SYNONYMS - sn-Glycero-3-phosphoethanolamine
SYNONYMS - 1-glycerophosphorylethanolamine\
[Data Chunk 2]
//
UNIQUE-ID - URIDINE
TYPES - Pyrimidine
....
....

每个文件中大约包含18000行(查看Notepad ++中的数据)。现在,我想创建一个新文件,并仅复制数据中的特定列。我只希望将这些列复制到新创建的文件中,并且该文件应如下所示-

UNIQUE-ID       TYPES        COMMON-NAME           CHEMICAL-FORMULA  BIGG ID    CHEMSPIDER ID    CAS ID    CHEBI ID    PUBCHEM ID    MOLECULAR-WEIGHT MONOISOTOPIC-MW

CPD0-1108    D-Ribofuranose  β-D-ribofuranose   C5H14N1O6P1      37147       NA                NA      10647       25200464        215.142       216.0636987293

URIDINE      Pyrimidine       ...

每个文件中的每个数据块不一定都具有我需要的所有列的信息,这就是为什么我在想要的输出表中为那些列提到了NA的原因。尽管在这些列中获取空白值是完全可以的,因为以后我可以分别处理这些空白。

这是具有数据的目录-

File 1] -> C:\Users\robbie\Desktop\Organism_Data\aact1035194-hmpcyc\compounds.dat
File 2] -> C:\Users\robbie\Desktop\Organism_Data\aaph679198-hmpcyc\compounds.dat
File 3] -> C:\Users\robbie\Desktop\Organism_Data\yreg1002368-hmpcyc\compounds.dat
File 4] -> C:\Users\robbie\Desktop\Organism_Data\tden699187-hmpcyc\compounds.dat
...
...

我真的很倾向于在R引用this的帖子中使用dir函数,但是当编写代码作为生物体名称(文件夹名称)时,我很困惑在函数的模式参数中添加什么)很奇怪,而且不一致。

非常感谢获得所需输出的任何帮助。我正在考虑在R中执行此操作的方法,但是如果我有很好的建议以及在python中处理此问题的方法,我也愿意在python中尝试此操作。在此先感谢您的帮助!

编辑: 链接到数据-Data

2 个答案:

答案 0 :(得分:1)

一个文件

将其分解为一些逻辑操作:

text2chunks <- function(txt) {
  chunks <- split(txt, cumsum(grepl("^\\[Data Chunk.*\\]$", txt)))
  Filter(function(a) grepl("^\\[Data Chunk.*\\]$", a[1]), chunks)
}
chunk2dataframe <- function(vec, hdrs = NULL, sep = " - ") {
  s <- stringi::stri_split(vec, fixed=sep, n=2L)
  s <- Filter(function(a) length(a) == 2L, s)
  df <- as.data.frame(setNames(lapply(s, `[[`, 2), sapply(s, `[[`, 1)),
                      stringsAsFactors=FALSE)
  if (! is.null(hdrs)) df <- df[ names(df) %in% make.names(hdrs) ]
  df
}

hdrs是要保留的列名的可选向量;如果未提供(或NULL),则所有键/值对将作为列返回。

hdrs <- c("UNIQUE-ID", "TYPES", "COMMON-NAME")

使用数据(如下),我有lines,它是来自单个文件的character向量:

head(lines)
# [1] "Authors:"                                                                              
# [2] "#    Pallavi Subhraveti"                                                               
# [3] "#    Quang Ong"                                                                        
# [4] "# Please see the license agreement regarding the use of and distribution of this file."
# [5] "# The format of this file is defined at http://bioinformatics.ai.sri.com"              
# [6] "# Version: 21.5"                                                                       
str(text2chunks(lines))
# List of 2
#  $ 1: chr [1:5] "[Data Chunk 1]" "UNIQUE-ID - CPD0-1108" "TYPES - D-Ribofuranose" "COMMON-NAME - &beta;-D-ribofuranose" ...
#  $ 2: chr [1:6] "[Data Chunk 2]" "// something out of place here?" "UNIQUE-ID - URIDINE" "TYPES - Pyrimidine" ...
str(lapply(text2chunks(lines), chunk2dataframe, hdrs=hdrs))
# List of 2
#  $ 1:'data.frame':    1 obs. of  3 variables:
#   ..$ UNIQUE.ID  : chr "CPD0-1108"
#   ..$ TYPES      : chr "D-Ribofuranose"
#   ..$ COMMON.NAME: chr "&beta;-D-ribofuranose"
#  $ 2:'data.frame':    1 obs. of  3 variables:
#   ..$ UNIQUE.ID  : chr "URIDINE"
#   ..$ TYPES      : chr "Pyrimidine"
#   ..$ COMMON.NAME: chr "&beta;-D-ribofuranose or something"

最终产品:

dplyr::bind_rows(lapply(text2chunks(lines), chunk2dataframe, hdrs=hdrs))
#   UNIQUE.ID          TYPES                        COMMON.NAME
# 1 CPD0-1108 D-Ribofuranose              &beta;-D-ribofuranose
# 2   URIDINE     Pyrimidine &beta;-D-ribofuranose or something

由于要在许多函数上进行迭代,因此为此创建一个便捷函数很有意义:

text2dataframe <- function(txt) {
  dplyr::bind_rows(lapply(text2chunks(txt), chunk2dataframe, hdrs=hdrs))
}

许多文件

未经测试,但应该可以工作:

files <- list.files(path="C:/Users/robbie/Desktop/Organism_Data/",
                    pattern="compounds.dat", recursive=TRUE, full.names=TRUE)
alldata <- lapply(files, readLines)
allframes <- lapply(alldata, text2dataframe)
oneframe <- dplyr::bind_rows(allframes)

注意:

  • 我只是为了方便起见使用stringi::stri_split而不是strsplit来使用n=;使用几行额外的代码,在R中进行相同的操作并不难。
  • 我使用dplyr::bind_rows是因为它可以很好地处理缺少的列和不同的顺序;基本rbind.data.frame可以省力/省心。
  • data.frame-大小化趋向于使列名稍微增加一点,请注意。

数据:

# lines <- readLines("some_filename.dat")
fulltext <- 'Authors:
#    Pallavi Subhraveti
#    Quang Ong
# Please see the license agreement regarding the use of and distribution of this file.
# The format of this file is defined at http://bioinformatics.ai.sri.com
# Version: 21.5
# File Name: compounds.dat
# Date and time generated: October 24, 2017, 14:52:45
# Attributes:
#    UNIQUE-ID
#    TYPES
[Data Chunk 1]
UNIQUE-ID - CPD0-1108
TYPES - D-Ribofuranose
COMMON-NAME - &beta;-D-ribofuranose
DO-NOT-CARE - 42
[Data Chunk 2]
// something out of place here?
UNIQUE-ID - URIDINE
TYPES - Pyrimidine
COMMON-NAME - &beta;-D-ribofuranose or something
DO-NOT-CARE - 43
'
lines <- strsplit(fulltext, '[\r\n]+')[[1]]

答案 1 :(得分:1)

另一种方法,在这种情况下,它仅读取您提供的文件,但可以读取多个文件。

我添加了一些中间结果以显示代码的实际作用...

library(tidyverse)
library(data.table)
library(zoo)

# create a data.frame with the desired files
filenames <- list.files( path = getwd(), pattern = "*.dat$", recursive = TRUE, full.names = TRUE ) 

# > filenames
#[1] "C:/Users/********/Documents/Git/udls2/test.dat"

#read in the files, using data.table's fread.. here I grep lines starting with UNIQUE-ID or TYPES. create your desired regex-pattern
pattern <- "^UNIQUE-ID|^TYPES"
content.list <- lapply( filenames, function(x) fread( x, sep = "\n", header = FALSE )[grepl( pattern, V1 )] )

# > content.list
# [[1]]
#                        V1
# 1:  UNIQUE-ID - CPD0-1108
# 2: TYPES - D-Ribofuranose
# 3:    UNIQUE-ID - URIDINE
# 4:     TYPES - Pyrimidine

#add all content to a single data.table
dt <- rbindlist( content.list )

# > dt
#                        V1
# 1:  UNIQUE-ID - CPD0-1108
# 2: TYPES - D-Ribofuranose
# 3:    UNIQUE-ID - URIDINE
# 4:     TYPES - Pyrimidine

#split the text in a variable-name and it's content
dt <- dt %>% separate( V1, into = c("var", "content"), sep = " - ")

# > dt
#          var        content
# 1: UNIQUE-ID      CPD0-1108
# 2:     TYPES D-Ribofuranose
# 3: UNIQUE-ID        URIDINE
# 4:     TYPES     Pyrimidine

#add an increasing id for every UNIQUE-ID
dt[var == "UNIQUE-ID", id := seq.int( 1: nrow( dt[var=="UNIQUE-ID", ]))]

# > dt
#          var        content id
# 1: UNIQUE-ID      CPD0-1108  1
# 2:     TYPES D-Ribofuranose NA
# 3: UNIQUE-ID        URIDINE  2
# 4:     TYPES     Pyrimidine NA

#fill down id vor all variables found
dt[, id := na.locf( dt$id )]

# > dt
#          var        content id
# 1: UNIQUE-ID      CPD0-1108  1
# 2:     TYPES D-Ribofuranose  1
# 3: UNIQUE-ID        URIDINE  2
# 4:     TYPES     Pyrimidine  2

#cast
dcast(dt, id ~ var, value.var = "content")

#    id          TYPES UNIQUE-ID
# 1:  1 D-Ribofuranose CPD0-1108
# 2:  2     Pyrimidine   URIDINE