How To Import Data Into R From Csv

When working with data analysis in R, it is common to come across datasets that are stored in CSV (Comma Separated Values) files. Importing data from CSV files into R is an essential skill for any data scientist. In this tutorial, you will learn how to easily import data from CSV files into R.

Step 1: Prepare a CSV file

Before importing the data into R, you need to have a CSV file. For this tutorial, we will use a sample dataset called students.csv with the following content:

Name,Age,Grade
Alice,14,8.5
Bob,15,7.5
Charlie,16,9
David,14,8

This CSV file contains data about students: their Name, Age, and Grade.

Step 2: Install and load required R packages

To read a CSV file in R, we will use the readr package, which is part of the tidyverse set of packages. First, install the package using the install.packages() function if you haven’t already:

Next, load the readr package using the library() function:

Step 3: Read the CSV file using read_csv() function

To read the CSV file, use the read_csv() function. Provide the file path as the argument:

In this example, the variable students will store the data imported from the students.csv file. Make sure to provide the correct file path.

Step 4: Display the imported data

Now that the CSV file is imported to R, you can display the data using the print() function:

Or, you can simply enter the variable name:

This will output the following data:

# A tibble: 4 × 3
  Name      Age Grade
  <chr>    <dbl> <dbl>
1 Alice      14   8.5
2 Bob        15   7.5
3 Charlie    16   9  
4 David      14   8  

Full code

Conclusion

In this tutorial, you learned how to import data from a CSV file into R using the readr package. This is a crucial skill to have when working with data analysis in R. Now, you should be able to load and analyze your own datasets. Happy analyzing!