Solution to readr task

1 Write a tibble to disk

First, I load the tidyverse package to have all readr functions available. Then I will write the tibble that I called animals from the previous task.

library(tidyverse)
# The variable animals with the tibble from the previous task
animals
# A tibble: 28 × 3
   species        bodywt_kg brainwt_kg
   <chr>              <dbl>      <dbl>
 1 MountainBeaver       1.4     0.0081
 2 Cow                465       0.423 
 3 GreyWolf            36.3     0.120 
 4 Goat                27.7     0.115 
 5 GuineaPig            1       0.0055
 6 Diplodocus       11700       0.05  
 7 AsianElephant     2547       4.60  
 8 Donkey             187.      0.419 
 9 Horse              521       0.655 
10 PotarMonkey         10       0.115 
# ℹ 18 more rows

Now I write the animals table into my project’s data/ folder:

write_csv(x = animals, file = "data/animals.csv") # write as csv
write_tsv(x = animals, file = "data/animals.txt") # write as txt
Note

In order for this command to work, the /data directory must already be present in your working directory. Otherwise the path cannot be found and you will get an error message.

2 Read data into R

Now I take the same data that I just wrote and read it back into R:

animals_csv <- read_csv("data/animals.csv") # read the csv
animals_tsv <- read_tsv("data/animals.txt") # read the txt
Note

I saved the data that I read in in two new variables: animals_csv and animals_tsv. You always need to do this, otherwise you don’t have the data available for the following analysis.

3 Extra

You can use the Files pane to import csv files. Just click on the csv file and then click on the Import Dataset button:

Now have the possibility to import a data set via a graphical user interface.

This is quite useful because you can preview your data and make sure that all the options are set correctly for importing. You can do this if you are not sure about the correct read_*() function arguments.

Just play with these different options of reading data into R and find one that fits you best.

This workflow is not reproducible. If you use this option to import data, you have to click the button every time you want to import the data set.

Importing the data set directly in your script using R code is the much better option. But check out the Code Preview window in the bottom right. You can just copy the code from there, paste it in your script and next time use the code instead of the graphical user interface.