我需要从互联网下载一个压缩的csv文件,将其解压缩并将其作为data.frame加载到内存中。有没有一种方法可以仅在不读取/写入磁盘的情况下完成内存中的整个过程?这是我尝试过的:
library(RCurl)
file <- getURL(url, userpwd='user:pwd')
tf <- tempfile()
writeBin(content(file, "raw"), tf)
tf <- unzip(tf, exdir=tempdir())
data <- read.csv(tf)
unlink(tf)
我认为这里的
writeBin
,unzip
和read.csv
使用昂贵的磁盘I/O,但我不知道如何改进它。
最佳答案
我认为使用unz()
的示例通过打开与Zip存档内单个文件的连接使您更接近某个地方,尽管如果unz()
函数实际上并未解压缩到磁盘,我会感到惊讶,但我没有对其进行检查:
## Create a sample data.frame object:
d <- data.frame(a=rnorm(40), b=rnorm(40))
## Write this data.frame to two separate CSV files, and zip
## them together into a new archive:
write.csv(d, file="d.csv")
write.csv(d, file="d_2.csv")
zip("d.zip", c("d.csv", "d_2.csv"))
## In this case, we will open a file connection to a single file
## inside the zip archive, and read the data in using read.csv():
f <- unz("d.zip", "d_2.csv")
a <- read.csv( f )
head(a)
关于r - 将原始文件解压缩到R中的内存中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32160232/