[r] R을 사용하여 압축 된 데이터 파일 다운로드, 데이터 추출 및 가져 오기

Twitter의 @EZGraphs는 “많은 온라인 csv가 압축되어 있습니다. R을 사용하여 아카이브를 다운로드하고 압축을 풀고 data.frame에 데이터를로드하는 방법이 있습니까? #Rstats”

오늘도이 작업을 수행하려고했지만 zip 파일을 수동으로 다운로드했습니다.

나는 다음과 같은 것을 시도했다.

fileName <- "http://www.newcl.org/data/zipfiles/a1.zip"
con1 <- unz(fileName, filename="a1.dat", open = "r")

하지만 나는 멀리 떨어져있는 것처럼 느낍니다. 이견있는 사람?



답변

Zip 아카이브는 실제로 콘텐츠 메타 데이터 등이있는 ‘파일 시스템’에 가깝습니다. 자세한 내용은를 참조 help(unzip)하십시오. 따라서 위에서 스케치 한 작업을 수행하려면

  1. 임시를 만듭니다. 파일 이름 (예를 들어 tempfile())
  2. download.file()파일을 임시로 가져 오는 데 사용 합니다. 파일
  3. unz()temp에서 대상 파일을 추출하는 데 사용 합니다. 파일
  4. 다음을 통해 임시 파일 제거 unlink()

코드에서 (기본 예제에 감사하지만 이것은 더 간단합니다)

temp <- tempfile()
download.file("http://www.newcl.org/data/zipfiles/a1.zip",temp)
data <- read.table(unz(temp, "a1.dat"))
unlink(temp)

압축 ( .z) 또는 gzip ( .gz) 또는 bzip2ed ( .bz2) 파일은 파일 일 뿐이며 연결에서 직접 읽을 수 있습니다. 따라서 데이터 공급자가 대신 사용하도록하십시오. 🙂


답변

기록을 위해 Dirk의 답변을 코드로 번역하려고했습니다.

temp <- tempfile()
download.file("http://www.newcl.org/data/zipfiles/a1.zip",temp)
con <- unz(temp, "a1.dat")
data <- matrix(scan(con),ncol=4,byrow=TRUE)
unlink(temp)


답변

http://cran.r-project.org/web/packages/downloader/index.html에있는 CRAN 패키지 “downloader”를 사용했습니다 . 훨씬 쉽게.

download(url, dest="dataset.zip", mode="wb")
unzip ("dataset.zip", exdir = "./")


답변

Mac의 경우 (그리고 Linux로 가정) …

우편 아카이브가 하나의 파일이 포함되어있는 경우, 당신은 bash는 명령을 사용할 수 있습니다 funzip와 연동 해에, fread로부터 data.table패키지 :

library(data.table)
dt <- fread("curl http://www.newcl.org/data/zipfiles/a1.zip | funzip")

아카이브에 여러 파일이 포함 된 경우 tar대신을 사용하여 특정 파일을 stdout으로 추출 할 수 있습니다 .

dt <- fread("curl http://www.newcl.org/data/zipfiles/a1.zip | tar -xf- --to-stdout *a1.dat")


답변

다음은 read.table함수 로 읽을 수없는 파일에 대해 작동하는 예입니다 . 이 예제는 .xls 파일을 읽습니다.

url <-"https://www1.toronto.ca/City_Of_Toronto/Information_Technology/Open_Data/Data_Sets/Assets/Files/fire_stns.zip"

temp <- tempfile()
temp2 <- tempfile()

download.file(url, temp)
unzip(zipfile = temp, exdir = temp2)
data <- read_xls(file.path(temp2, "fire station x_y.xls"))

unlink(c(temp, temp2))


답변

data.table을 사용하여이를 수행하기 위해 다음이 작동 함을 발견했습니다. 불행히도 링크가 더 이상 작동하지 않으므로 다른 데이터 세트에 대한 링크를 사용했습니다.

library(data.table)
temp <- tempfile()
download.file("https://www.bls.gov/tus/special.requests/atusact_0315.zip", temp)
timeUse <- fread(unzip(temp, files = "atusact_0315.dat"))
rm(temp)

bash 스크립트를에 전달할 수 있기 때문에 한 줄로 가능하다는 것을 알고 fread있지만 .zip 파일을 다운로드하고 추출하여 단일 파일을 fread.


답변

이 코드를 사용해보십시오. 나를 위해 작동합니다.

unzip(zipfile="<directory and filename>",
      exdir="<directory where the content will be extracted>")

예:

unzip(zipfile="./data/Data.zip",exdir="./data")