Using R to download zipped data file, extract, and import .csv

前端 未结 3 1845
無奈伤痛
無奈伤痛 2020-12-06 01:07

I am trying to download and extract a .csv file from a webpage using R.

This question is a duplicate of Using R to download zipped data file, extrac

相关标签:
3条回答
  • 2020-12-06 01:11

    It's almost everything ok. In this case you only need to specify that it's a comma separated file, eg using sep="," in read.table:

    temp <- tempfile()
    download.file("http://api.worldbank.org/v2/en/country/gbr?downloadformat=csv", 
                  temp)
    con <- unz(temp, "gbr_Country_en_csv_v2.csv")
    dat <- read.table(con, header=T, skip=2, sep=",")
    unlink(temp)
    

    With this little change i can import your csv smoothly.

    HTH, Luca

    0 讨论(0)
  • 2020-12-06 01:27

    The Word Bank Developmet Indictors can be obtained using the WDI package. For example,

    library(WDI)
    inds <- WDIsearch(field = "indicator")[, 1]
    GB <- WDI("GB", indicator = inds)
    

    See WDIsearch and WDI functions and the rerference manual for more info.

    0 讨论(0)
  • 2020-12-06 01:36

    In order to get your data to download and uncompress, you need to set mode="wb"

    download.file("...",temp, mode="wb")
    unzip(temp, "gbr_Country_en_csv_v2.csv")
    dd <- read.table("gbr_Country_en_csv_v2.csv", sep=",",skip=2, header=T)
    

    It looks like the default is "w" which assumes a text files. If it was a plain csv file this would be fine. But since it's compressed, it's a binary file, hence the "wb". Without the "wb" part, you can't open the zip at all.

    0 讨论(0)
提交回复
热议问题