Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags


How to import CSV and text files in R

Saad Qadeer

Import CSV files in R

To load an excel based dataset file, navigate to "File" -> "Import Dataset" -> "From Excel":


The read function

We can also use the read.csv or the read_csv functions to load the file in RStudio.

Step 1

  • To use the read functions, we need to install the tidyverse package if not already installed on our system:
  • After installation, we can load the library:

Step 2

  • Use the setwd() function to specify the project’s working directory, if not already done. The working directory on our system contains the data files of the project we're working on:

Step 3

  • Use the read.csv() or the read_csv() with the file name passed as the argument:
data <- read.csv('File_Name.csv')
data <- read_csv('File_Name.csv')
  • We can also pass the complete file path and the file name as an argument to the read.csv() and read_csv() functions to import the CSV file.
data <- read.csv('File Path/File_Name.csv')
data <- read_csv('File Path/File_Name.csv')
  • If we pass the complete file path into the read functions, there is no need to set the working directory using the setwd() function.

The fread() function

We can load the data.table library to make use of the fread() function to read the CSV files.

The fread() function is more efficient in speed and memory consumption than the read_csv() function.

Step 1

  • To use the fread() function, we need to install the data.table package if not already installed on our system:

After Installation, we load the data.table library:


Step 2

After we load the library, we can now call the fread() function:

data <- fread('File Path/File_Name.csv')

Import text files in R

One way of importing text data into R Studio is to navigate to "File" -> "Import Dataset" -> "From Text":


After selecting the desired file, a panel will open where we can choose various data attributes, such as the encoding and separators, and import the data:


The read function

Similar to read.csv(), we can also use the read function for text files using the read.delim() variant:

data <- read.delim("File Path/File_Name.txt",sep = "\t", header=FALSE)

Import text from URL

We can directly use data from the web and load it in R studio without ever having to download the data in our local directory using the read.table() function. Only the data set URL has to be passed as an argument to the function:

textFile_url <- ''
data <- read.table(textFile_url, header = TRUE)

The file.choose() Method

A comparatively easier way to load files into R would be to use the file.chose() passed as an argument to the read functions:

data <- read.csv(file.choose())
data <- read.delim(file.choose())



View all Courses

Keep Exploring