The readr
package helps us read all sorts of files into R. In this tutorial we will be focusing on how to read in and save csv files in R using read_csv
and write_csv
. First, if you haven’t installed the readr package, go ahead and do that by running the line of code below
install.packages('readr')
Next let’s practice with the mtcars data set that is already made available to us in R. Run the line below to load the readr
package and to get the mtcars data set into your environment.
library(readr)
mtcars <- mtcars
Now let’s try saving this data set as a csv to our computer. We will do this using the write_csv
function. This function has two main arguments: x
and path
. The x
argument is the data set that you want to save, which in this case is the mtcars data set that we just saved to our environment. The path
argument is the file path where you want to save the file. The end of the path
argument is the name that you want to use for the file. See the example below. Before running the example below, create a new folder in your Documents folder called example-data. After running the line below you should be able to see this file in the example-data folder in your Documents.
write_csv(x = mtcars, "example-data/mtcars.csv")
Now let’s practice with read_csv
by reading this file back into R. The read_csv
has one main argument: file
. The file
argument is the file path to the file that you are wanting to read into R. Running the line below will read the csv back into R and save it in our environment as mtcars2. You can see that it’s the exact same as the mtcars data set that we loaded earlier.
mtcars2 <- read_csv("example-data/mtcars.csv")
This tutorial should give you everything you need to read your own data into R and continue practicing some of the data visualization and data wrangling skills you have already developed!