library(readr)
<- read_csv("data/DatasaurusDozen.csv", show_col_types = FALSE)
dino_data View(dino_data)
2 Importing Data into R
2.1 CSV format
We will read data in r by loading the example data DatasaurusDozen.csv
. You can download the zip file containing the data here.
After saving the unzipped downloaded folder data
in the same folder as your .Rproj
, you can import the file with the following line of code:
- Using the
head()
-function provides you with an easy and quick way to check whether your data was imported correctly. - You can use the
View()
-function to inspect your data.
2.2 Data from Excel
Importing data from Excel into R, you can use the read_excel()
-function.
You will have to install the readxl()
-package before you can use the read_excel()
-function.
2.3 Useful functions
There are a few useful functions that provide you with easy and quick ways to check your imported data.
With the
View()
function will give you a spreadsheet-like rendering of your data. Don’t forget to write a capitalised V.The
head()
-function is an easy way to check whether your data was imported correctly by displaying a a certain amount of rows. You can specify how many rows should be shown in the function’s argument.With the
names()
-function returns a character vector containing your variable names.
2.3.1 Common import mistakes
If the following error message appears, it means that your working directory is not set correctly.
Error in file(file, "rt") : cannot open the connection
In addition: Warning message: In file(file, "rt") : cannot open file
'data/DatasaurusDozen.csv': No such file or directory
If you save your data in a designated data
folder located on the same level as your .Rproj
-file, you should not encounter any error messages regarding your working directory. Do not forget to start your R-session by opening your .Rproj
-file (not by opening your scripts).
2.4 Save data
You can also save data from your R session as csv files. Before you can export your data from R, you will have to transform your data into a DataFrame. You can do so by adapting the following line of code:
<- data.frame(column1 = c("val 1", "val 2", "val 3", ...),
dataFrame column2 = c("val1", "val 2", "val 3", ...)
)
Afterwards, you can export your data by using the write.csv()
-function:
write.csv(dataFrame, "path of where you want to save your file/example_data.csv")
At the end of the file path, you specify the file name (here “example_data.csv”).