The Wayback Machine - https://web.archive.org/web/20240830075805/https://www.geeksforgeeks.org/reading-files-in-r-programming/
Open In App

Reading Files in R Programming

Last Updated : 01 Aug, 2023
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

So far the operations using the R program are done on a prompt/terminal which is not stored anywhere. But in the software industry, most of the programs are written to store the information fetched from the program. One such way is to store the fetched information in a file. So the two most common operations that can be performed on a file are:

  • Importing/Reading Files in R
  • Exporting/Writing Files in R

Reading Files in R Programming Language

When a program is terminated, the entire data is lost. Storing in a file will preserve our data even if the program terminates. If we have to enter a large number of data, it will take a lot of time to enter them all. However, if we have a file containing all the data, we can easily access the contents of the file using a few commands in R. You can easily move your data from one computer to another without any changes. So those files can be stored in various formats. It may be stored in a i.e..txt(tab-separated value) file, or in a tabular format i.e .csv(comma-separated value) file or it may be on the internet or cloud. R provides very easier methods to read those files.

File reading in R

One of the important formats to store a file is in a text file. R provides various methods that one can read data from a text file.

  • read.delim(): This method is used for reading “tab-separated value” files (“.txt”). By default, point (“.”) is used as decimal point.

Syntax: read.delim(file, header = TRUE, sep = “\t”, dec = “.”, …)

Parameters:

  • file: the path to the file containing the data to be read into R.
  • header: a logical value. If TRUE, read.delim() assumes that your file has a header row, so row 1 is the name of each column. If that’s not the case, you can add the argument header = FALSE.
  • sep: the field separator character. “\t” is used for a tab-delimited file.
  • dec: the character used in the file for decimal points.

Example: 

R




# R program reading a text file
 
# Read a text file using read.delim()
myData = read.delim("geeksforgeeks.txt", header = FALSE)
print(myData)


Output: 

1 A computer science portal for geeks.

Note: The above R code, assumes that the file “geeksforgeeks.txt” is in your current working directory. To know your current working directory, type the function getwd() in R console.

  • read.delim2(): This method is used for reading “tab-separated value” files (“.txt”). By default, point (“,”) is used as decimal points.

Syntax: read.delim2(file, header = TRUE, sep = “\t”, dec = “,”, …)

Parameters:

  • file: the path to the file containing the data to be read into R.
  • header: a logical value. If TRUE, read.delim2() assumes that your file has a header row, so row 1 is the name of each column. If that’s not the case, you can add the argument header = FALSE.
  • sep: the field separator character. “\t” is used for a tab-delimited file.
  • dec: the character used in the file for decimal points.

Example: 

R




# R program reading a text file
 
# Read a text file using read.delim2
myData = read.delim2("geeksforgeeks.txt", header = FALSE)
print(myData)


Output: 

1 A computer science portal for geeks.
  • file.choose(): In R it’s also possible to choose a file interactively using the function file.choose(), and if you’re a beginner in R programming then this method is very useful for you.

Example: 
 

R




# R program reading a text file using file.choose()
 
myFile = read.delim(file.choose(), header = FALSE)
# If you use the code above in RStudio
# you will be asked to choose a file
print(myFile)


Output: 

1 A computer science portal for geeks.
  • read_tsv(): This method is also used for to read a tab separated (“\t”) values by using the help of readr package.

Syntax: read_tsv(file, col_names = TRUE)

Parameters:

  • file: the path to the file containing the data to be read into R.
  • col_names: Either TRUE, FALSE, or a character vector specifying column names. If TRUE, the first row of the input will be used as the column names.

Example: 

R




# R program to read text file
# using readr package
 
# Import the readr library
library(readr)
 
# Use read_tsv() to read text file
myData = read_tsv("geeksforgeeks.txt", col_names = FALSE)
print(myData)


Output: 

# A tibble: 1 x 1
X1

1 A computer science portal for geeks.

Note: You can also use file.choose() with read_tsv() just like before. 

# Read a txt file
myData <- read_tsv(file.choose())

Reading one line at a time

read_lines(): This method is used for the reading line of your own choice whether it’s one or two or ten lines at a time. To use this method we have to import reader package.

Syntax: read_lines(file, skip = 0, n_max = -1L)

Parameters:

  • file: file path
  • skip: Number of lines to skip before reading data
  • n_max: Numbers of lines to read. If n is -1, all lines in the file will be read.

Example: 

R




# R program to read one line at a time
 
# Import the readr library
library(readr)
 
# read_lines() to read one line at a time
myData = read_lines("geeksforgeeks.txt", n_max = 1)
print(myData)
 
# read_lines() to read two line at a time
myData = read_lines("geeksforgeeks.txt", n_max = 2)
print(myData)


Output: 

[1] "A computer science portal for geeks."

[1] "A computer science portal for geeks."
[2] "Geeksforgeeks is founded by Sandeep Jain Sir."

Reading the whole file

read_file(): This method is used for reading the whole file. To use this method we have to import reader package.

Syntax: read_lines(file)

file: the file path

Example: 

R




# R program to read the whole file
 
# Import the readr library
library(readr)
 
# read_file() to read the whole file
myData = read_file("geeksforgeeks.txt")
print(myData)


Output:

[1] “A computer science portal for geeks.\r\nGeeksforgeeks is founded by Sandeep Jain Sir.\r\nI am an intern at this amazing platform.”

Reading a file in a table format

Another popular format to store a file is in a tabular format. R provides various methods that one can read data from a tabular formatted data file.

read.table(): read.table() is a general function that can be used to read a file in table format. The data will be imported as a data frame.

Syntax: read.table(file, header = FALSE, sep = “”, dec = “.”)

Parameters:

  • file: the path to the file containing the data to be imported into R.
  • header: logical value. If TRUE, read.table() assumes that your file has a header row, so row 1 is the name of each column. If that’s not the case, you can add the argument header = FALSE.
  • sep: the field separator character
  • dec: the character used in the file for decimal points.

Example: 

R




# R program to read a file in table format
 
# Using read.table()
myData = read.table("basic.csv")
print(myData)


Output:

1 Name,Age,Qualification,Address
2 Amiya,18,MCA,BBS
3 Niru,23,Msc,BLS
4 Debi,23,BCA,SBP
5 Biku,56,ISC,JJP

read.csv(): read.csv() is used for reading “comma separated value” files (“.csv”). In this also the data will be imported as a data frame.

Syntax: read.csv(file, header = TRUE, sep = “,”, dec = “.”, …)

Parameters:

  • file: the path to the file containing the data to be imported into R.
  • header: logical value. If TRUE, read.csv() assumes that your file has a header row, so row 1 is the name of each column. If that’s not the case, you can add the argument header = FALSE.
  • sep: the field separator character
  • dec: the character used in the file for decimal points. 
     

Example: 

R




# R program to read a file in table format
 
# Using read.csv()
myData = read.csv("basic.csv")
print(myData)


Output: 

Name Age Qualification Address
1 Amiya 18 MCA BBS
2 Niru 23 Msc BLS
3 Debi 23 BCA SBP
4 Biku 56 ISC JJP

read.csv2(): read.csv() is used for variant used in countries that use a comma “,” as decimal point and a semicolon “;” as field separators.

Syntax: read.csv2(file, header = TRUE, sep = “;”, dec = “,”, …)

Parameters:

  • file: the path to the file containing the data to be imported into R.
  • header: logical value. If TRUE, read.csv2() assumes that your file has a header row, so row 1 is the name of each column. If that’s not the case, you can add the argument header = FALSE.
  • sep: the field separator character
  • dec: the character used in the file for decimal points. 
     

Example: 

R




# R program to read a file in table format
 
# Using read.csv2()
myData = read.csv2("basic.csv")
print(myData)


Output: 

Name.Age.Qualification.Address
1 Amiya,18,MCA,BBS
2 Niru,23,Msc,BLS
3 Debi,23,BCA,SBP
4 Biku,56,ISC,JJP

file.choose(): You can also use file.choose() with read.csv() just like before.

Example: 

R




# R program to read a file in table format
 
# Using file.choose() inside read.csv()
myData = read.csv(file.choose())
# If you use the code above in RStudio
# you will be asked to choose a file
print(myData)


Output: 

Name Age Qualification Address
1 Amiya 18 MCA BBS
2 Niru 23 Msc BLS
3 Debi 23 BCA SBP
4 Biku 56 ISC JJP

read_csv(): This method is also used for to read a comma (“,”) separated values  by using the help of readr package.

Syntax: read_csv(file, col_names = TRUE)

Parameters:

  • file: the path to the file containing the data to be read into R.
  • col_names: Either TRUE, FALSE, or a character vector specifying column names. If TRUE, the first row of the input will be used as the column names.

Example: 

R




# R program to read a file in table format
# using readr package
 
# Import the readr library
library(readr)
 
# Using read_csv() method
myData = read_csv("basic.csv", col_names = TRUE)
print(myData)


Output: 

Parsed with column specification:
cols(
Name = col_character(),
Age = col_double(),
Qualification = col_character(),
Address = col_character()
)
# A tibble: 4 x 4
Name Age Qualification Address

1 Amiya 18 MCA BBS
2 Niru 23 Msc BLS
3 Debi 23 BCA SBP
4 Biku 56 ISC JJP

Reading a file from the internet

It’s possible to use the functions read.delim(), read.csv() and read.table() to import files from the web.

Example: 

R




# R program to read a file from the internet
 
# Using read.delim()
print(head(myData))


Output: 


Nom variable Group
1 IND1 10 A
2 IND2 7 A
3 IND3 20 A
4 IND4 14 A
5 IND5 14 A
6 IND6 12 A


Previous Article
Next Article

Similar Reads

Reading Tabular Data from files in R Programming
Often, the data which is to be read and worked upon is already stored in a file but is present outside the R environment. Hence, importing data into R is a mandatory task in such circumstances. The formats which are supported by R are CSV, JSON, Excel, Text, XML, etc. The majority of times, the data to be read into R is in tabular format. The funct
4 min read
Reading and Writing Excel Files With R Using readxl and writexl
In this article let's discuss reading and writing excel files using readxl and writexl packages of the R programming language. read_excel() method in readxl Package:The Readxl package is used to read data from the excel files i.e. the files of format .xls and .xlsx. The Readxl package provides a function called read_excel() which is used to read th
3 min read
Reading contents of a Text File in R Programming - read.table() Function
The read.table() function in R can be used to read a text file's contents. A versatile and often used function for reading tabular data from different file formats, including text files, is read.table(). It returns the data in the form of a table. Syntax: read.table(filename, header = FALSE, sep = "") Parameters: header: represents if the file cont
3 min read
Working with XML Files in R Programming
XML which stands for Extensible Markup Language is made up of markup tags, wherein each tag illustrates the information carried by the particular attribute in the XML file. We can work with the XML files using the XML package provided by R. The package has to be explicitly installed using the following command: install.packages("XML")Creating XML f
3 min read
Working with Excel Files in R Programming
Excel files are of extension .xls, .xlsx and .csv(comma-separated values). To start working with excel files in R Programming Language, we need to first import excel files in RStudio or any other R supporting IDE(Integrated development environment). Reading Excel Files in R Programming Language First, install readxl package in R to load excel files
3 min read
Writing to Files in R Programming
R programming Language is one of the very powerful languages specially used for data analytics in various fields. Analysis of data means reading and writing data from various files like excel, CSV, text files, etc. Today we will be dealing with various ways of writing data to different types of files using R programming. R - Writing to Files Writin
2 min read
Working with Binary Files in R Programming
In the computer science world, text files contain data that can easily be understood by humans. It includes letters, numbers, and other characters. On the other hand, binary files contain 1s and 0s that only computers can interpret. The information stored in a binary file can't be read by humans as the bytes in it translate to characters and symbol
5 min read
Working with JSON Files in R Programming
JSON stands for JavaScript Object Notation. These files contain the data in human readable format, i.e. as text. Like any other file, one can read as well as write into the JSON files. In order to work with JSON files in R, one needs to install the "rjson" package. The most common tasks done using JSON files under rjson packages are as follows: Ins
4 min read
How to Write Multiple Excel Files From Column Values - R programming
A data frame is a cell-based structure comprising rows and columns belonging to the same or different data types. Each cell in the data frame is associated with a unique value, either a definite value or a missing value, indicated by NA. The data frame structure is in complete accordance with the Excel sheet structure. Therefore, the data frame val
6 min read
Working with CSV files in R Programming
In this article, we will discuss how to work with CSV files in R Programming Language. R CSV Files R CSV Files are text files wherein the values of each row are separated by a delimiter, as in a comma or a tab. In this article, we will use the following sample CSV file. Getting and Setting the Working Directory with R CSV Files C/C++ Code # Get the
4 min read
Reading the CSV file into Dataframes in R
In this article, we will learn how to import or read a CSV file into a dataframe in R Programming Language. Data set in use: Step 1: Set or change the working directory In order to import or read the given CSV file into our data frame, we first need to check our current working directory, and make sure that the CSV file is in the same directory as
3 min read
Specify Row Names when Reading Excel File in R
In this article, we are going to specify the row names when reading Excel file in the R Programming language. Specifying row names when reading a file using row.names argument of the read.xlsx2() function. This is the easiest approach to specify the row names when reading a file in the R programming language as in this approach the user needs to ju
2 min read
Reading Google Sheets In R
In this article, we are going to see how to read google sheets in R Programming Language. Method 1: Using googlesheets4 Before moving forward we need to Installing the googlesheets4 package into the working space. The googlesheets4 package in R is used to read and access the contents of a google sheet. It can be used to read as well as write the me
3 min read
Reading large numeric TSV file into memory in R
TSV (Tab-Separated Values) files are a common way of storing data. When working with large numeric TSV files in the R programming language, memory issues can arise when reading them in. Fortunately, there are several R packages and functions available to help with this task, including readr and data.table. The readr package provides a read_tsv() fu
4 min read
What is the Relation Between R Programming and Hadoop Programming?
The relation between R programming and Hadoop revolves around integrating R with the Hadoop ecosystem to analyze large datasets that are stored in a Hadoop environment. R, primarily used for statistical analysis and data visualization, is not inherently built for handling big data. However, when combined with Hadoop, it can leverage Hadoop's distri
3 min read
How to read column names and metadata from feather files in R arrow?
To access column names and metadata from feather files in R programming, we use the R Arrow package to load the feather file into a data frame. After loading the feather file, we can retrieve the column names and metadata attributes by using the Feather package. What is Arrow Package in R? The Arrow package available in R offers a range of tools to
3 min read
Save and Load RData Workspace Files in R
In this article, we will discuss how to save and load R data workspace files in R programming language. Method 1: Using save.image and load method The save.image method in R is used to save the current workspace files. It is an extended version of the save method in R which is used to create a list of all the declared data objects and save them int
3 min read
Writing to CSV files in R
For Data Analysis sometimes creating CSV data file is required and do some operations on it as per our requirement. So, In this article we are going to learn that how to write data to CSV File using R Programming Language. To write to csv file write.csv() function is used. Syntax: write.csv(data, path) Parameter: data: data to be added to csvpath:
1 min read
Merge multiple CSV files using R
In this article, we will be looking at the approach to merge multiple CSV files in the R programming language. In this approach to merge multiple CSV files, the user needs to install and import three different packages namely- dplyr,plyr, and readr in the R programming language console to call the functions which are list.files(), lapply(), and bin
2 min read
Read all Files in Directory using R
To list all files in a directory in R programming language we use list.files(). This function produces a list containing the names of files in the named directory. It returns a character vector containing the names of the files in the specified directories. If no files are present in the directory, it returns "". If a path does not exist it is skip
2 min read
Import and Merge Multiple CSV Files in R
In this article, we will be looking at the approach to merge multiple CSV files in the R programming language. Modules Useddplyr: This is a structure of data manipulation that provides a uniform set of verbs, helping to resolve the most frequent data manipulation hurdles.plyr: plyr is an R package that makes it simple to split data apart, do stuff
2 min read
List all Files with Specific Extension in R
R programming language contains a wide variety of method to work with directory and its associated sub-directories. There are various inbuilt methods in R programming language which are used to return the file names with the required extensions. It can be used to efficiently locate the presence of a file. Directory in use: Method 1 : Using list.fil
3 min read
How to read multiple Excel files in R
In this article, we will discuss how to merge multiple Excel files in the R programming language. Modules Used:dplyr: The dplyr package in R is a structure of data manipulation that provides a uniform set of verbs, helping to resolve the most frequent data manipulation hurdles.plyr: The “plyr” package in R is used to work with data, including its e
2 min read
Rename Files Using R
In this article, we are going to see how to rename files using R Programming Language. To rename a file in R we use file.rename(). This function renames all the files mentioned as parameters. It returns normally TRUE for success, FALSE for failure. Note: File naming conventions depend on the platform. Syntax: file.rename( to, from) Parameters: to:
1 min read
How to Import SAS Files into R?
In this article, we are going to see how to import SAS files(.sas7bdat) into R Programming Language. SAS stands for Statistical Analysis Software, it contains SAS program code saved in a propriety binary format. The R packages discussed, haven and sas7bdat, involved reverse engineering this propriety format. Used File: Click Method 1: Using haven P
1 min read
How to Import SPSS Files into R?
In this article, we are going to see how to import SPSS Files(.sav files) into R Programming Language. Used file: Click Method 1: Using haven Package Here we will use the haven package to import the SAS files. To install the package: install.packages('haven') To import the SAV file read_sav() methods are capable to read the file. Syntax: read_sav('
1 min read
How to Read xls files from R using gdata
Reading xls files from R using gdata is a useful way to import and manipulate data in R Programming Language. The gdata package provides a set of functions for reading and writing data in various file formats, including xls files. In this article, we will discuss the concepts related to reading xls files in R using gdata, the steps needed to do so,
3 min read
Read RData Files in R
In this article we are going to see how to read R File using R Programming Language. We often have already written R scripts that can be reused using some simple code. Reading R Programming Language code from a file allows us to use the already written code again, enabling the possibility to update the code, keep the project clean, and share the ba
3 min read
How to edit CSV files in R
In this article, we are going to learn how to edit CSV files in the R programming language. What is a CSV file? A Comma Separated Values (CSV) file is a simple plain text file that contains a list of data separated by a delimiter. As the name implies in these files the information stored is separated by a comma. R has built-in functionality of CSV
4 min read
How to Import TSV Files into R
In this article, we are going to discuss how to import tsv files in R Programming Language. The TSV is an acronym for Tab Separated Values, in R these types of files can be imported using two methods one is by using functions present in readr package and another method is to import the tsv file by specifying the delimiter as tab space('\t') in read
2 min read
Article Tags :