4. Import & Export Data

flowchart LR
    A["`**Step 1**
    Scripts & Projects`"] --> B["`**Step 2**
    Working Directory`"] --> C["`**Step 3**
    Libraries`"] --> D["`**Step 4**
    Import & Export`"]
    style D fill:#1a1a1a,stroke:#1a1a1a,color:#fff
    linkStyle default stroke:#adb5bd,stroke-width:2px

Importing Data

One of the biggest roadblocks to using R is getting data into R and accessible. R can only work with data when it is imported into R’s working memory and named as an object. Most datasets you will need to load into R are “.csv” files. But R supports loading and saving many different file formats, which can be determined by the letters after a saved file’s name like file_name.csv or file_name.xlsx.

Here is how we load data into R:

test_data <- read_csv("first_data.csv")
Run this example — load a dataset and check its class

Which of the following is a class of test_data?

Troubleshooting file names

Remember R requires you to be very precise with names of files. Sometimes you might be getting error messages and can’t figure out why. The command dir() returns all the file names in your current working directory. I will sometimes run dir() and copy and paste the file name into read_csv().

Exporting Data

Now lets say you wanted to save an object as a “.csv”. Use the function write_csv():

write_csv(test_data, "my_output.csv")