如何用EOF解决fread txt的问题?

DrX*_*DrX 5 import r data.table

我试图从ftp://ftp.ncdc.noaa.gov/pub/data/ghcn/daily/ghcnd-stations.txt上读取气候站信息.但是,由于第一行未完全填充(缺少最后两个cols)并且第5列包含空格,因此我无法完成阅读:

fread('ftp://ftp.ncdc.noaa.gov/pub/data/ghcn/daily/ghcnd-stations.txt',sep=)
Run Code Online (Sandbox Code Playgroud)

它返回错误消息:

 Expected sep (' ') but new line, EOF (or other non printing character) ends 
 field 5 when detecting types from point 0: AGE00135039  35.7297    0.6500   
 50.0    ORAN-HOPITAL MILITAIRE     
Run Code Online (Sandbox Code Playgroud)

如何在阅读此txt文件时正确应用fread?谢谢!

Edw*_*ard 0

为什么不尝试一下read.fwfutils 包中的功能呢?readme.txt 文件中给出了列宽(请参阅第 IV 节)。

IV. FORMAT OF "ghcnd-stations.txt"

------------------------------
Variable   Columns   Type
------------------------------
ID            1-11   Character
LATITUDE     13-20   Real
LONGITUDE    22-30   Real
ELEVATION    32-37   Real
STATE        39-40   Character
NAME         42-71   Character
GSN FLAG     73-75   Character
HCN/CRN FLAG 77-79   Character
WMO ID       81-85   Character
------------------------------
Run Code Online (Sandbox Code Playgroud)

但是,以下尝试会返回错误:

data <- read.fwf("ghcnd-stations.txt", widths = c(11,9,10,7,3,31,4,4,6))
Error in scan(file = file, what = what, sep = sep, quote = quote, dec = dec,  : 
  line 25383 did not have 7 elements
Run Code Online (Sandbox Code Playgroud)

检查第 25,383 行可以发现错误的原因。

> x <- readLines("ghcnd-stations.txt", 25383)
> tail(x, 1)
[1] "CA002100627  60.8167 -137.7333  846.0 YT HAINES APPS #4                              "
Run Code Online (Sandbox Code Playgroud)

因此,可以通过包含comment.char参数、将值从默认值 (#) 更改为其他值(可能只是 null)来规避此问题。

data <- read.fwf("ghcnd-stations.txt", widths = c(11,9,10,7,3,31,4,4,6), comment.char="")
Run Code Online (Sandbox Code Playgroud)

只需要大约20秒。没有真正的需要fread