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

问题描述 投票:5回答:1

我正在尝试阅读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?谢谢!

r import data.table
1个回答
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参数来绕过这一点,将值从默认值(#)更改为其他值,可能只是null。

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

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

© www.soinside.com 2019 - 2024. All rights reserved.