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

时间:2017-09-11 19:14:28

标签: r import 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=)

它返回错误消息:

 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     

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

1 个答案:

答案 0 :(得分:0)

为什么不尝试使用utils包中的read.fwf函数?列宽在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
------------------------------

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

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

第25,383行的检查揭示了错误的原因。

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

因此,通过包含comment.char参数,将值从默认值(#)更改为其他值,可能只是空值来绕过这一点。

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

只需20秒左右。不需要fread