Home » How to Download Files from the Internet Using R

How to Download Files from the Internet Using R

by Tutor Aspire

You can use the following basic syntax to download a file from the internet using the R programming language:

download.file(url, destfile)

where:

  • url: A character string that contains the URL of the file
  • destfile: A character string that contains the location of where to save the file

The following step-by-step example shows how to use this syntax in practice.

Step 1: Find URL of File

For this example, I’ll download a CSV file that contains information about model aircraft fields in New York located at the following URL:

https://catalog.data.gov/dataset?res_format=CSV&organization=city-of-new-york

To get the exact URL for this CSV file, I’ll right click on the CSV button and then click Copy link address:

I’ll then save this URL as a string variable in R:

#define URL location
url

Step 2: Define Destination for File

Next, I’ll define the destination to save the file to:

#define destination for file
destfile 

Step 3: Download and View File

Next, I’ll use the following code to download the file:

#download file and save in specified destination
download.file(url, destfile)

Lastly, I’ll navigate to the Downloads file where I saved the CSV file:

If I double click the file, I can open and view the contents:

Additional Resources

The following tutorials explain how to work with other types of files in R:

How to Import CSV Files into R
How to Import Excel Files into R
How to Import SPSS Files into R
How to Import SAS Files into R
How to Import Stata Files into R

You may also like