簡體   English   中英

當較大的行沒有出現在文件的早期時,R data.table fread無法讀取不規則的列長度

[英]R data.table fread cannot read in irregular column lengths when the larger rows do not appear early in a file

我想使用data.table函數fread讀取csv文件。 csv文件包含大量包含9列的記錄,然后是包含10列的大量記錄。 使用參數fill=TRUE不能解決問題。 以下是一些演示我的問題的示例數據:

library(data.table)
short <- rep("1,1,1", 1000)
long <- rep("1,1,1,2", 1000)
write(c(short, long), "shortLong.csv")
write(c(long, short), "longShort.csv")

當我讀入具有短列長度然后長列長度的文件時,我收到此錯誤:

fread("shortLong.csv", fill=TRUE)
Error in fread("shortLong.csv", fill = TRUE) : 
  Expecting 3 cols, but line 1001 contains text after processing all cols. Try again with fill=TRUE. Another reason could be that fread's logic in distinguishing one or more fields having embedded sep=',' and/or (unescaped) '\n' characters within unbalanced unescaped quotes has failed. If quote='' doesn't help, please file an issue to figure out if the logic could be improved

但是,當我讀取具有長列長度然后短列長度的文件時,它會在文件中讀取沒有問題,並使用NA填充短列中的缺失值,這是我想要的:

fread("longShort.csv", fill=TRUE)
      V1 V2 V3 V4
   1:  1  1  1  2
   2:  1  1  1  2
   3:  1  1  1  2
   4:  1  1  1  2
   5:  1  1  1  2
  ---            
1996:  1  1  1 NA
1997:  1  1  1 NA
1998:  1  1  1 NA
1999:  1  1  1 NA
2000:  1  1  1 NA

這個錯誤似乎是由長列之前的大量短列引起的,因為當我將short和long混合在一起時沒有問題:

mixed <- rep(c("1,1,1", "1,1,1,2"), 1000)
write(mixed, "mixed.csv")
fread("mixed.csv", fill=TRUE)
      V1 V2 V3 V4
   1:  1  1  1 NA
   2:  1  1  1  2
   3:  1  1  1 NA
   4:  1  1  1  2
   5:  1  1  1 NA
  ---            
1996:  1  1  1  2
1997:  1  1  1 NA
1998:  1  1  1  2
1999:  1  1  1 NA
2000:  1  1  1  2

我懷疑這種行為上的差異可能是因為fread向前看分配列但是沒有查看整個文件並根據看到的最長時間設置最大列數(但我不熟悉函數的內部工作方式)。

有沒有辦法使用fread正確讀取我的數據? 我想我可能會把一些hacky解決方案放在一起並繞過fread ,但我喜歡這個性能而且我不想大幅減慢代碼速度。 謝謝!

請注意,您擁有的不是 csv文件,因為它沒有標頭。 如果我們添加標題,它將起作用。 首先使用fread將其作為每行的單個字段讀取,給出字符向量Lines 從那里計算出最大字段數n 最后在用標題作為前綴后重新讀取Lines

Lines <- fread("shortLong.csv", sep = "")[[1]]
n <- max(count.fields(textConnection(Lines), sep = ","))
fread(text = c(toString(1:n), Lines), header = TRUE, fill = TRUE)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM