繁体   English   中英

R data.table fread命令:如何读取带有不规则分隔符的大文件?

[英]R data.table fread command : how to read large files with irregular separators?

我必须处理120个~2 GB(525600行×302列)文件的集合。 目标是制作一些统计数据并将结果放在干净的SQLite数据库中。

当我的脚本使用read.table()导入时,一切正常,但速度很慢。 所以我尝试使用fread,来自data.table包(版本1.9.2),但它给了我这个错误:

Error in fread(txt, header = T, select = c("YYY", "MM", "DD",  : 
Not positioned correctly after testing format of header row. ch=' '

我的数据的前2行和7行看起来像这样:

 YYYY MM DD HH mm             19490             40790
 1991 10  1  1  0      1.046465E+00      1.568405E+00

因此,开头有第一个空格,日期列之间只有一个空格,其他列之间有任意数量的空格。

我试过用这样的命令来转换逗号中的空格:

DT <- fread(
            paste("sed 's/\\s\\+/,/g'", txt),
            header=T,
            select=c('HHHH','MM','DD','HH')
)

没有成功:问题仍然存在,使用sed命令似乎很慢。

Fread似乎不喜欢“任意数量的空间”作为分隔符或开头的空列。 任何想法 ?

这是(可能)最小的可重复示例(40790之后的换行符):

txt<-print(" YYYY MM DD HH mm             19490             40790
 1991 10  1  1  0      1.046465E+00      1.568405E+00")

testDT<-fread(txt,
              header=T,
              select=c("YYY","MM","DD","HH")
)

谢谢你的帮助 !

更新 : - data.table 1.8。*不会发生错误。 在这个版本中,表被读作一个唯一的行,这并不是更好。

更新2 - 如评论中所述,我可以使用sed格式化表格然后用fread读取它。 我在上面的答案中放了一个脚本,在那里我创建了一个样本数据集,然后比较一些system.time()。

致力于发展,v1.9.5。 fread()获得带有默认TRUE strip.white参数(而不是base::read.table() ,因为它更合乎需要)。 现在,示例数据已添加到测试中。

通过最近的提交:

require(data.table) # v1.9.5, commit 0e7a835 or more recent
ans <- fread(" YYYY MM DD HH mm             19490             40790\n   1991 10  1  1  0      1.046465E+00      1.568405E+00")
#      V1 V2 V3 V4 V5           V6           V7
# 1: YYYY MM DD HH mm 19490.000000 40790.000000
# 2: 1991 10  1  1  0     1.046465     1.568405
sapply(ans, class)
#          V1          V2          V3          V4          V5          V6          V7 
# "character" "character" "character" "character" "character"   "numeric"   "numeric" 
sed 's/^[[:blank:]]*//;s/[[:blank:]]\{1,\}/,/g' 

为你sed

不可能将fread的所有结果收集到1(临时)文件中(添加源引用)并使用sed(或其他工具)处理此文件以避免在每次迭代时分叉工具?

通过NeronLeVelu和Clayton Stanlay的答案,我用自定义函数,示例数据和一些system.time()完成了答案,以便进行比较。 这些测试是在Mac OS 10.9和R 3.0.2上进行的。 但是,我在linux机器上进行了相同的测试,并且sed命令的执行速度非常慢,而read.table()则预先计算了nrows和colClasses。 fread部分非常快,两个系统上的5e6行大约需要5秒。

library(data.table)


# create path to new temporary file
origData <- tempfile(pattern="origData",fileext=".txt")
# write table with irregular blank spaces separators.
write(paste0(" YYYY MM DD HH mm             19490             40790","\n",
                 paste(rep(" 1991 10  1  1  0      1.046465E+00      1.568405E+00", 5e6), 
                       collapse="\n"),"\n"),
      file=origData
)

# define column classes for read.table() optimization
colClasses <- c(rep('integer',5),rep('numeric',2))

# Function to count rows with command wc for read.table() optimization.
fileRowsCount <- function(file){
    if(file.exists(file)){
            sysCmd <- paste("wc -l", file)
            rowCount <- system(sysCmd, intern=T)
            rowCount <- sub('^\\s', '', rowCount)
        as.numeric(
                       strsplit(rowCount, '\\s')[[1]][1]
                      )
    }
}

# Function to sed data into temp file before importing with sed
sedFread<-function(file, sedCmd=NULL, ...){
    require(data.table)
    if(is.null(sedCmd)){
        #default : sed for convert blank separated table to csv. Thanks NeronLevelu !
        sedCmd <- "'s/^[[:blank:]]*//;s/[[:blank:]]\\{1,\\}/,/g'"
    }
    #sed into temp file
    tmpPath<-tempfile(pattern='tmp',fileext='.txt')
    sysCmd<-paste('sed',sedCmd, file, '>',tmpPath)
    try(system(sysCmd))
    DT<-fread(tmpPath,...)
    try(system(paste('rm',tmpPath)))
    return(DT)
}

Mac OS结果:

# First sed into temp file and then fread.
system.time(
DT<-sedFread(origData, header=TRUE)
)
> user  system elapsed
> 23.847   0.628  24.514

# Sed directly in fread command :
system.time(
DT <- fread(paste("sed 's/^[[:blank:]]*//;s/[[:blank:]]\\{1,\\}/,/g'", origData),
            header=T)
)
> user  system elapsed
> 23.606   0.515  24.219


# read.table without nrows and colclasses
system.time(
DF<-read.table(origData, header=TRUE)
)
> user  system elapsed
> 38.053   0.512  38.565

# read.table with nrows an colclasses
system.time(
DF<-read.table(origData, header=TRUE, nrows=fileRowsCount(origData), colClasses=colClasses)
)
> user  system elapsed
> 33.813   0.309  34.125

Linux结果:

# First sed into temp file and then fread.
system.time(
  DT<-sedFread(origData, header=TRUE)
)
> Read 5000000 rows and 7 (of 7) columns from 0.186 GB file in 00:00:05
> user  system elapsed 
> 47.055   0.724  47.789 

# Sed directly in fread command :
system.time(
DT <- fread(paste("sed 's/^[[:blank:]]*//;s/[[:blank:]]\\{1,\\}/,/g'", origData),
            header=T)
)
> Read 5000000 rows and 7 (of 7) columns from 0.186 GB file in 00:00:05
> user  system elapsed 
> 46.088   0.532  46.623 

# read.table without nrows and colclasses
system.time(
DF<-read.table(origData, header=TRUE)
)
> user  system elapsed 
> 32.478   0.436  32.912 

# read.table with nrows an colclasses
system.time(
DF<-read.table(origData,
               header=TRUE, 
               nrows=fileRowsCount(origData),
               colClasses=colClasses)
 )
> user  system elapsed 
> 21.665   0.524  22.192 

# Control if DT and DF are identical : 
setnames(DT, old=names(DT), new=names(DF))
identical(as.data.frame(DT), DF)                                                              
>[1] TRUE

很好:在这种情况下,我首先使用的方法是最有效的。

感谢NeronLeVelu,Matt Dowle和Clayton Stanley!

我找到了另一种方法,用awk而不是sed更快地完成它。 这是另一个例子:

library(data.table)

# create path to new temporary file
origData <- tempfile(pattern="origData",fileext=".txt")

# write table with irregular blank spaces separators.
write(paste0(" YYYY MM DD HH mm             19490             40790","\n",
            paste(rep(" 1991 10  1  1  0      1.046465E+00      1.568405E+00", 5e6),
            collapse="\n"),"\n"),
            file=origData
  )


# function awkFread : first awk, then fread. Argument : colNums = selection of columns. 
awkFread<-function(file, colNums, ...){
        require(data.table)
        if(is.vector(colNums)){
            tmpPath<-tempfile(pattern='tmp',fileext='.txt')
            colGen<-paste0("$",colNums,"\",\"", collapse=",")
            colGen<-substr(colGen,1,nchar(colGen)-3)
            cmdAwk<-paste("awk '{print",colGen,"}'", file, '>', tmpPath)
            try(system(cmdAwk))
            DT<-fread(tmpPath,...)
            try(system(paste('rm', tmpPath)))
            return(DT)
        }
}

# check read time :
system.time(
            DT3 <- awkFread(origData,c(1:5),header=T)
            )

> user  system elapsed 
> 6.230   0.408   6.644

如果峰值内存不是问题,或者您可以将其以可管理的块流式传输,则以下gsub() / fread()混合应该可以工作,将所有连续空格字符转换为您选择的单个分隔符(例如"\\t" ) ,在通过fread()解析之前:

fread_blank = function(inputFile, spaceReplace = "\t", n = -1, ...){
  fread(
    input = paste0(
      gsub(pattern = "[[:space:]]+",
           replacement = spaceReplace,
           x = readLines(inputFile, n = n)),
      collapse = "\n"),
    ...)
}

我必须同意其他人认为空格分隔的文件不是理想的选择,但我经常遇到它们是否喜欢它。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM