How to Use R to Download File from Internet (Example)

 

In this article, I’ll explain how to use the R programming language to download a file from the internet.

Let’s dive right in!

 

Step 1: Get URL of File

First, we need to copy the URL where our data is stored.

In this example, I’m going to use a csv file from this website: https://www.stats.govt.nz/large-datasets/csv-files-for-download/

On the website, you can find a list of downloadable csv files. Right click on one of them and copy the link location:

 

How to copy a URL

Figure 1: Get Link Location of csv File.

 

Now, store this link location as character string in R:

# Specify URL where file is stored
url <- "https://www.stats.govt.nz/assets/Uploads/Annual-enterprise-survey/Annual-enterprise-survey-2017-financial-year-provisional/Download-data/annual-enterprise-survey-2017-financial-year-provisional-csv.csv"

 

Step 2: Set File Destination

In addition to the link location, we also need to specify where on our computer we want to save the data. The following R code illustrates how to define the path of the output directory:

# Specify destination where file should be saved
destfile <- "C:/Users/ ... Your Path ... /my folder/output.csv"

 

Step 3: Download File with R

We are ready to download!

The base R function download.file enables us to download our file and save it in the specified directory. We simply need to tell the function the URL (Step 1) and the file destination (Step 2):

# Apply download.file function in R
download.file(url, destfile)

Have a look at the folder that you have specified as file destination. You should find the downloaded data in csv format:

 

Downloaded csv File

Figure 2: Downloaded csv File in Folder on Computer.

Note: R allows for the download of any file format you want. In the previous example, we have downloaded a csv file. However, you might also download Excel (xlsx / xls) files, txt files, zip files, PDF files and so on. Furthermore, it is possible to download files from a sharepoint or a web application such as shiny.

 

Video Example & Further Resources

Do you need further guidance for the downloading of files from the web? Then you could have a look at the following video of DevNami’s YouTube channel.

The video does not only show another example for the application of the download.file function. It also explains how to import this data to R (or RStudio).

 

 

In addition, you might also want to have a look at the other R tutorials on this website. I’m publishing new R and statistics tutorials regularly:

This article explained how to download data from the internet with the download.file R function. I case you have any further questions, let me know in the comments.

 



 

Leave a Reply

Your email address will not be published. Required fields are marked *

Fill out this field
Fill out this field
Please enter a valid email address.

Menu
Top