Importing Data
Before you start: selecting table columns; project folders and relative paths.
Setup: Save the supplied Quakes CSV as Data/quakes.csv. Create Output/ and start from the project root.
Your check: Inspect an import and compare CSV and RDS round trips. Practise in the unit summary.
If function calls or named arguments are new to you, first work through R Syntax with its supplied three-row file. For a project-folder setup and a first path check, use Work Environment. This page extends that workflow to other file formats and a real earthquake dataset.
Choose your route: the core workflow starts at Importing data via code, then uses the supplied Quakes CSV. Save the commands in a script so that you can repeat the import. The button-based route below is an optional alternative; you do not need to complete both routes or install readr for the code workflow.
Importing data via buttons
The data import features can be accessed from the environment pane or from the tools menu. The importers are grouped into 3 categories: Text data, Excel data and statistical data. To access this feature, use the “Import Dataset” dropdown from the “Environment” pane:
Or through the “File” menu, followed by the “Import Dataset” submenu:
The From Text (readr) option uses the additional readr package; follow RStudio’s installation prompt if you choose it. This is an optional import route. The code workflow below uses functions supplied with R, so it does not require readr.
The readr text importer supports CSV and other character-delimited files, with options to:
- Import from the file system or a URL
- Change column data types
- Skip or include-only columns
- Rename the data set
- Skip the first n rows
- Use the header row for column names
- Trim spaces in names
- Change the column delimiter
- Encoding selection
- Select quote, escape, comment and NA identifiers
Importing data via code
Reading or writing tabular data is a common task in data analysis. Use read.table() or read.csv() to import a text file into a data frame.
The following code blocks are templates. Replace "path/to/your/file.csv" with the path to your own file before running them. read.csv() assumes comma-separated columns and a decimal point; read.csv2() assumes semicolon-separated columns and a decimal comma.
df <- read.csv("path/to/your/file.csv")
With read.table(), you can specify the format explicitly. This template reads whitespace-separated values without a header. Adjust header, sep, dec, and skip to match your file:
df <- read.table("path/to/your/file.csv", header = FALSE, sep = "",
dec = ".", skip = 0)
Reading data from csv files
For the following example, use the course’s quakes.csv. This replacement teaching dataset is a CSV export of R’s built-in quakes data: 1,000 seismic events near Fiji, with five columns. The data come from the Harvard PRIM-H project, which obtained them from Dr. John Woodhouse at Harvard University. See the R dataset documentation and the CSV source and export notes.
Create Data/ and Output/ folders inside your RStudio project folder. Download quakes.csv and save it as Data/quakes.csv. Open your .Rproj file so that the working directory is the project folder; check it with getwd().
The CSV export keeps all original data values and adds four metadata lines before the column header. It uses semicolons between columns and decimal commas. Import it with read.table():
df <- read.table("Data/quakes.csv",
skip = 4, header = TRUE, sep = ";", dec = ",")
As you can see, the read.table function gets several arguments (which is common for many functions). The first one gives the filename including the path to the file.
skip = 4tells the function to skip the four metadata lines added to this teaching CSVheader = TRUEtells the function, that the csv file has a header line which is used byread.tableto name the columns of the returning data framesep = ";"defines the separator of the individual columns in the data framedec = ","defines the decimal separator used in the dataset
A note on the sequence of the arguments: the sequence of the arguments does
not matter as long as you name them explicitly. If you do not use the argument
identifier as it is the case for the first argument, the filename, in the example
then the sequence matters. To get information on the default sequence and of
course the general application of each R function, type ?<function name>
(e.g. ?read.table) in an R console.
After running the import, df contains a data frame with 1,000 rows and five columns: latitude (lat), longitude (long), depth in kilometers (depth), reported magnitude (mag), and the number of reporting stations (stations). Inspect the column types with str():
str(df)
'data.frame': 1000 obs. of 5 variables:
$ lat : num -20.4 -20.6 -26 -18 -20.4 ...
$ long : num 182 181 184 182 182 ...
$ depth : int 562 650 42 626 649 195 82 194 211 622 ...
$ mag : num 4.8 4.2 5.4 4.1 4 4 4.8 4.4 4.7 4.3 ...
$ stations: int 41 15 43 19 11 12 43 15 35 19 ...
Use head(df, 2) to display the first two rows of the imported data frame. Without an explicit row count, head(df) shows the first six rows, or all rows if there are fewer than six. This is a useful first inspection; it does not by itself confirm that every column was imported correctly.
head(df, 2)
lat long depth mag stations
1 -20.42 181.62 562 4.8 41
2 -20.62 181.03 650 4.2 15
Writing data to csv files
Use write.table() to export df to the Output/ folder you created above. This example uses comma-separated columns and a decimal point. row.names = FALSE omits R’s row names from the file:
write.table(df, file = "Output/quakes-export.csv", sep = ",", dec = ".",
row.names = FALSE)
The exported file starts directly with the column header; it does not include the four metadata lines from the input file. Read it back with read.csv() and compare the imported and exported data frames:
df_csv <- read.csv("Output/quakes-export.csv")
identical(df, df_csv)
[1] TRUE
For this numeric dataset, the values, column types, and names match after export and re-import. CSV does not preserve every kind of R object or attribute; use RDS when you want to store an R object for use in R.
For more information, see the R manual: data import, the R manual: text export, or the help pages for read.table() and write.table().
Alternative data I/O using RDS
CSV is useful for exchanging tabular data with other programs. To save a single R object for later use in R, use saveRDS() and restore it with readRDS(). RDS preserves the object’s R structure and attributes, such as column types and factor levels. The file extension .rds is commonly used for this format.
The following code writes quakes.rds in Output/ and reads the object back into df2:
saveRDS(df, file = "Output/quakes.rds")
# Restore the saved object under a different name
df2 <- readRDS("Output/quakes.rds")
identical(df, df2)
[1] TRUE
See ?saveRDS and ?readRDS for more details.
Example: Importing Destatis data
Continue with Example: Importing Destatis data, a separate worked example using the official 2024 land-use report.
The import and inspection steps show how to preserve identifiers and inspect empty cells in the current source table.
The column selection and conversion steps include detailed English explanations of the German names, codes, units, and geographic levels.