There are three different methods available to import CSV file in R.
The following methods show how you can do it with syntax.
Method 1: Use read.csv() Function
data <- read.csv("path_of_file",header=TRUE)
Method 2: Use read_csv() from readr Package
library(readr)
data <- read_csv("path_of_file")
Method 3: Use fread from data.table Package
library(data.table)
data <- fread("path_of_file")
Let’s see example for each method how we can achieve importing CSV in R.
Import CSV file Using read.csv in R
You can use read.csv function to import CSV also you can set header as TRUE or FALSE
# Import CSV file
data <- read.csv("R studio\\product.csv",header=TRUE)
# Display imported data
print(data)
Output:
Product Count
1 Cylinder 12
2 Sensor 6
3 Display 2
4 Monitor 1
The output shows data read from product.csv file.
We can use read.csv() function when you have smaller files.
Import CSV File Using read_csv in R
When you are working on large files you can use read_csv() function from readr package:
# Install package
install.packages("readr")
# Import library
library(readr)
# Import CSV file
data <- read_csv("R studio\\product.csv")
# Display imported data
print(data)
Output:
Product Count
<chr> <dbl>
1 Cylinder 12
2 Sensor 6
3 Display 2
4 Monitor 1
The output shows data from CSV file which read using read_csv function.
Import CSV File Using fread() in R
For extremely large files you can use fread() function from data.table package:
# Install package
install.packages("data.table")
# Import library
library(data.table)
# Import CSV file
data <- fread("R studio\\product.csv")
# Display imported data
print(data)
Output:
Product Count
1: Cylinder 12
2: Sensor 6
3: Display 2
4: Monitor 1
Here the output shows data from product.csv file which read using fread function.
While providing file path you need to use double backslashes (\) to avoid error.