You can use the following basic syntax to download a file from the internet using the R programming language:
- 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:
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<-"https://data.cityofnewyork.us/api/views/brsj-szf5/rows.csv?accessType=DOWNLOAD"
Step 2: Define Destination for File
Next, I’ll define the destination to save the file to:
#define destination for file destfile <- "C:/Users/Bob/Downloads"
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:
The following tutorials explain how to work with other types of files in R: