R:读取压缩的二进制文件

时间:2011-05-27 15:32:48

标签: r

我正在尝试用R解析一些在线天气数据。数据是一个已经过压缩的二进制文件。示例文件是:

ftp://ftp.cpc.ncep.noaa.gov/precip/CPC_UNI_PRCP/GAUGE_GLB/V1.0/2005/PRCP_CU_GAUGE_V1.0GLB_0.50deg.lnx.20050101.gz

如果我将文件下载到计算机并手动解压缩,我可以轻松执行以下操作:

  myFile <- ( "/tmp/PRCP_CU_GAUGE_V1.0GLB_0.50deg.lnx.20050101" )
  to.read = file( myFile, "rb")
  myPoints <- readBin(to.read, real(), n=1e6, size = 4, endian = "little")

我更喜欢做的是自动下载/解压缩以及读取。所以我认为这将简单如下:

p <- gzcon( url( "ftp://ftp.cpc.ncep.noaa.gov/precip/CPC_UNI_PRCP/GAUGE_GLB/V1.0/2005/PRCP_CU_GAUGE_V1.0GLB_0.50deg.lnx.20050101.gz" ) )
myPoints <- readBin(p, real(), n=1e6, size = 4, endian = "little")

这似乎只是花花公子,但在手动步骤中,向量myPoints的长度为518400,这是准确的。但是,如果R处理下载和读取,如第二个示例中所示,每次运行代码时,我都会得到不同的长度向量。认真。我不抽烟。我发誓。我运行它多次,每次矢量长度不同,总是小于预期的518400.

我还尝试让R使用以下内容下载gzip文件:

temp <- tempfile()
myFile <- download.file("ftp://ftp.cpc.ncep.noaa.gov/precip/CPC_UNI_PRCP/GAUGE_GLB/V1.0/2005/PRCP_CU_GAUGE_V1.0GLB_0.50deg.lnx.20050101.gz",temp)

我发现通常会返回关于文件不是预期大小的警告。如下所示:

Warning message:
In download.file("ftp://ftp.cpc.ncep.noaa.gov/precip/CPC_UNI_PRCP/GAUGE_GLB/V1.0/2005/PRCP_CU_GAUGE_V1.0GLB_0.50deg.lnx.20050101.gz",  :
  downloaded length 162176 != reported length 179058

你能提出哪些建议可以帮我解决这个问题?

-J

1 个答案:

答案 0 :(得分:2)

试试这个:

R> remfname <- "ftp://ftp.cpc.ncep.noaa.gov/precip/CPC_UNI_PRCP/GAUGE_GLB/V1.0/2005/PRCP_CU_GAUGE_V1.0GLB_0.50deg.lnx.20050101.gz"
R> locfname <- "/tmp/data.gz"
R> download.file(remfname, locfname)
trying URL 'ftp://ftp.cpc.ncep.noaa.gov/precip/CPC_UNI_PRCP/GAUGE_GLB/V1.0/2005/PRCP_CU_GAUGE_V1.0GLB_0.50deg.lnx.20050101.gz'
ftp data connection made, file length 179058 bytes
opened URL
==================================================
downloaded 174 Kb

R> con <- gzcon(file(locfname, "rb"))
R> myPoints <- readBin(con, real(), n=1e6, size = 4, endian = "little")
R> close(con)
R> str(myPoints)
 num [1:518400] 0 0 0 0 0 0 0 0 0 0 ...
R> 
相关问题