Import and Export Data with readr

Slides in full screen     Download PDF slides

1 Task

Note

Find the solution here.

1.1 Get started with readr and the tidyverse

Before you start, make sure to install the tidyverse packages by calling

install.packages("tidyverse")

This will install readr along with other tidyverse packages.

Remember to put library(tidyverse) (or library(readr)) on top of your script to access the readr functions.

1.1.1 Write a tibble to disk

Let’s use the animals tibble from the previous task and write it into the data folder in our project.

Before writing the tibble

  • Create a data sub-folder in your RStudio project (if you don’t have one yet)
    • Hint: You can do that from within RStudio by using the New Folder button in the Files pane

Now write the animals tibble into that /data sub-directory as animals.csv using a comma separator.

Check if the file was written into the correct folder.

1.2 Read data into R

Now, try to read the data set back into R using the appropriate read_* function.

Make sure that you save the table you read in in a new variable to have it available for later use.

Tip

Don’t type the input path of the table to read. Instead, make the “” to start writing the path and then us the tab key on your keyboard to auto-complete.

1.3 Extra

  • Try reading some tables (xlsx, csv, txt, …) that you have on your machine into R
    • First copy the table into the data/ folder in your project, then use the appropriate function to read in the data
    • Ideally, you use some of your research data, so you can see what are the difficulties there. Alternatively, you can use any kind of table even if not related to research.
  • Download the csv or excel file using the buttons below. The files have metadata on top and a messy header. The excel file has the added difficulty, that the actual data is not in the first sheet but in the second one. Try reading it into R correctly and clean the column names using the janitor::clean_names function. It might help to look at the data first to decide how to read it correctly.