读取错误“预期的sep('')但是..”

时间:2015-03-10 17:18:12

标签: r data.table

fread {data.table}在使用标签分隔文件时出现问题,该文件具有部分引用的行。我无法找到解决方法,因为它会自动处理引号(因此quote没有read.csv参数。这表明:

str1 = 'L1\tsome\tunquoted\tstuff\nL2\tsome\t"half" quoted\tstuff\nL3\tthis\t"should work"\tok thought'
str2 = gsub('"', '', str1)

fread(str2, sep='\t', header=F, skip=0L)
#    V1   V2          V3         V4
# 1: L1 some    unquoted      stuff
# 2: L2 some half quoted      stuff
# 3: L3 this should work ok thought
fread(str1, sep='\t', header=F, skip=0L)
# Error in fread(str1, sep = "\t", header = F, skip = 0L) : 
#   Expected sep (' ') but '
# ' ends field 3 on line 1 when detecting types: L2 some    "half" quoted   stuff

有没有办法解决这个问题,除了在原始文件上执行查找/替换之外?

1 个答案:

答案 0 :(得分:2)

stringi呢?很容易理解,非常有效。还有一个函数stri_read_lines(),用于从文件中读取/分割行。

library(stringi)

as.data.frame(stri_split_fixed(stri_split_lines1(str1), "\t", simplify = TRUE))
#   V1   V2            V3         V4
# 1 L1 some      unquoted      stuff
# 2 L2 some "half" quoted      stuff
# 3 L3 this "should work" ok thought

如果您需要确信这是一种比read.*()更有效的方法,请在应用于解析为30k行的扁平字符串时查看上述方法的时序。您还可以通过调整as.data.frame()中的参数来加快速度。对于此示例,stringi方法的速度大约是read.table()的两倍。

str1 <- "L1\tsome\tunquoted\tstuff\nL2\tsome\t\"half\" quoted\tstuff\nL3\tthis\t\"should work\"\tok thought"

library(stringi)
library(microbenchmark)

write(stri_flatten(rep(str1, 1e5), collapse = "\n"))
file.info("data")[1]
#         size
# data 8400000

microbenchmark(
    stringi = {
        mat <- stri_split_fixed(stri_read_lines("data"), "\t", simplify = TRUE)
        out <- as.data.frame(mat)
    },
    read.table = {
        out2 <- read.table("data", sep = "\t", quote = "\n")
    },
    times = 3L,
    unit = "relative"
)

# Unit: relative
#        expr      min       lq     mean   median      uq      max neval cld
#     stringi 1.000000 1.000000 1.000000 1.000000 1.00000 1.000000     3  a 
#  read.table 2.074071 2.111722 1.997857 2.148897 1.96356 1.808365     3   b

identical(out, out2)
# [1] TRUE