简体   繁体   English

无法在 R 中打开临时文件

[英]Trouble opening a tempfile in R

I am trying and failing to use a tempfile() to get data from a .gz file posted on the web without writing the archive to my hard drive and manually extracting the desired file.我正在尝试使用tempfile()从发布在网络上的 .gz 文件中获取数据,但未能将存档写入我的硬盘驱动器并手动提取所需的文件。 I'm re-using code that has worked in similar situations before, and R can find other tempfiles with no trouble.我正在重用以前在类似情况下工作过的代码,R 可以毫无问题地找到其他临时文件。

Here's the code I'm using:这是我正在使用的代码:

temp <- tempfile()
download.file("http://unified-democracy-scores.org/files/20140312/z/uds_summary.csv.gz", temp)
UDS <- read.csv(unz(temp, "uds_summary.csv"), stringsAsFactors = FALSE)

Here's the error it's throwing:这是它抛出的错误:

Error in open.connection(file, "rt") : cannot open the connection
In addition: Warning message:
In open.connection(file, "rt") :
  cannot open zip file 'C:\Users\Jay\AppData\Local\Temp\RtmpKs4ZWm\file100877485507'

I tried setting the mode in download.file() to other options (eg, mode="wb" ) to no avail.我尝试将download.file()的模式设置为其他选项(例如, mode="wb" )无济于事。 Ditto for varying the method at that step.在该步骤中改变方法也是如此。 If I download the archive to my hard drive and manually extract the .csv using the name used in the third line of my code, it reads in fine.如果我将存档下载到我的硬盘驱动器并使用我的代码第三行中使用的名称手动提取 .csv,它读取正常。

Any ideas what I'm doing wrong here?任何想法我在这里做错了什么?

Use gzfile instead of unz :使用gzfile而不是unz

UDS <- read.csv(gzfile(temp), stringsAsFactors = FALSE)

This gives the output:这给出了输出:

head(UDS)
#>         country year cowcode     mean        sd   median    pct025
#> 1 United States 1946       2 1.086431 0.2962744 1.072743 0.5424734
#> 2 United States 1947       2 1.094423 0.2989538 1.077987 0.5516301
#> 3 United States 1948       2 1.050040 0.2604016 1.038927 0.5642550
#> 4 United States 1949       2 1.039801 0.2585845 1.031048 0.5628056
#> 5 United States 1950       2 1.084971 0.2449264 1.071610 0.6280569
#> 6 United States 1951       2 1.043591 0.2551857 1.033722 0.5695530
#>     pct975
#> 1 1.694063
#> 2 1.719771
#> 3 1.588783
#> 4 1.567912
#> 5 1.589253
#> 6 1.577150

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM