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:
1 |
install.packages("readr") |
Next, load the readr package using the library() function:
1 |
library(readr) |
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:
1 |
students <- read_csv("students.csv") |
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:
1 |
print(students) |
Or, you can simply enter the variable name:
1 |
students |
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
1 2 3 4 5 6 7 8 |
#Load readr package library(readr) #Read CSV file students <- read_csv("C:/temp/students.csv") #Display data students |
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!