The Wayback Machine - https://web.archive.org/web/20241127232826/https://www.geeksforgeeks.org/data-handling-in-r-programming/
Open In App

Data Handling in R Programming

Last Updated : 10 May, 2020
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

R Programming Language is used for statistics and data analytics purposes. Importing and exporting of data is often used in all these applications of R programming.
R language has the ability to read different types of files such as comma-separated values (CSV) files, text files, excel sheets and files, SPSS files, SAS files, etc.

R allows its users to work smoothly with the systems directories with the help of some pre-defined functions that take the path of the directory as the argument or return the path of the current directory that the user is working on. Below are some directory functions in R:

  • getwd(): This function is used to get the current working directory being used by R.
  • setwd(): This function in R is used to change the path of current working directory and the path of the directory is passed as argument in the function.
    Example:

    setwd("C:/RExamples/")
    

    OR

    setwd("C:\\RExamples\\")
    
  • list.files(): This function lists all files and folders present in current working directory.

Importing Files in R

Let us take some basic files to import in R to learn the approach of importing data files:

Importing Text Files

In R language, text files can be read using read.table() function.

Syntax:

read.table(filename, header = FALSE, sep = "")

Parameters:
header represents if the file contains header row or not
sep represents the delimiter value used in file

To know about all the arguments of read.table(), execute below command in R:

help("read.table")

Example:
Suppose a file is present in the current working directory and using R programming, import the data from that particular text file and the content of text file is as shown:

100 A a
200 B b
300 C c
400 D d
500 E e
600 F f

Values are separated by white spaces.




# Check current working directory
getwd()
  
# Get content into a data frame
data <- read.table("TextFileExample.txt", 
                    header = FALSE, sep = " ")
  
# Printing content of Text File
print(data)
  
# Print the class of data
print(class(data))


Output:

[1] "C:/Users/xyz/Documents"
   V1 V2 V3
1 100  A  a
2 200  B  b
3 300  C  c
4 400  D  d
5 500  E  e
6 600  F  f
[1] "data.frame"

Importing CSV Files

Comma separated values or CSV files can be imported and read in R using read.csv() function.

Syntax:

read.csv(filename, header = FALSE, sep = "")

Parameters:
header represents if the file contains header row or not
sep represents the delimiter value used in file

To know about all the arguments of read.csv(), execute below command in R:

help("read.csv")

Example:
Suppose a csv file is present in the current working directory and the content of file is as shown:




# Check current working directory
getwd()
  
# Get content into a data frame
data <- read.csv("CSVFileExample.csv", 
                  header = FALSE,sep = "\t")
  
# Printing content of Text File
print(data)
  
# Print the class of data
print(class(data))


Output:

[1] "C:/Users/xyz/Documents"
   V1 V2 V3
1 100 AB ab
2 200 CD cd
3 300 EF ef
4 400 GH gh
5 500 IJ ij
[1] "data.frame"

Importing Excel File

To read and import the excel files, “xlsx” package is required to use the read.xlsx() function. To read “.xls” excel files, “gdata” package is required to use read.xls() function.

Syntax:

read.xlsx(filename, sheetIndex)

OR

read.xlsx(filename, sheetName)

Parameters:
sheetIndex specifies number of sheet
sheetName specifies name of sheet

To know about all the arguments of read.xlsx(), execute below command in R:

help("read.xlsx")

Example:
Suppose a xlsx file is present in the current working directory and the content of file is as shown:




# Install xlsx package
install.packages("xlsx")
  
library(xlsx)
  
# Check current working directory
getwd()
  
# Get content into a data frame
data <- read.xlsx("ExcelExample.xlsx", 
                   sheetIndex = 1, 
                   header = FALSE)
  
# Printing content of Text File
print(data)
  
# Print the class of data
print(class(data))


Output:

[1] "C:/Users/xyz/Documents"
    X1  X2  X3
1 1000 ABC abc
2 2000 DEF def
3 3000 GHI ghi
4 4000 JKL jkl
5 5000 MNO mno
[1] "data.frame"

Exporting files in R

Below are some methods to export the data to a file in R:

  • Using console
    cat() function in R is used to output the object to console. It can be also used as redirecting the output to a particular file.

    Syntax:

    cat(..., file)
    

    Parameter:
    file specifies the filename to which output has to redirected

    To know about all the arguments of cat(), execute below command in R:

    help("cat")

    Example:




    str = "World"
      
    # Redirect Output to file 
    cat("Hello, ", str, file = "catExample.txt")

    
    

    Output:
    Above code creates a new file and redirects the output of cat(). The contents of the file are shown below after executing the code-

    Hello,  World
    
  • Using sink() function:
    sink() function is used to redirect all the outputs from cat() and print() to the given filename.
    Syntax:

    sink(filename) # begins redirecting output to file
    .
    .
    sink()
    

    To know about all the arguments of sink(), execute below command in R:

    help("sink")

    Example:




    # Begin redirecting output
    sink("SinkExample.txt")
      
    x <- c(1, 3, 4, 5, 10)
    print(mean(x))
    print(class(x))
    print(median(x))
      
    sink()

    
    

    Output:
    The above code creates a new file and redirects the output. The contents of the file are shown below after executing the code-

    [1] 4.6
    [1] "numeric"
    [1] 4
    

Writing to CSV files

A matrix or data-frame object can be redirected and written to csv file using write.csv() function.

Syntax: write.csv(x, file)

Parameter:
file specifies the file name used for writing

To know about all the arguments of write.csv(), execute below command in R:

help("write.csv")

Example:




# Create vectors
x <- c(1, 3, 4, 5, 10)
y <- c(2, 4, 6, 8, 10)
z <- c(10, 12, 14, 16, 18)
  
# Create matrix
data <- cbind(x, y, z)
  
# Writing matrix to CSV File
write.csv(data, file = "CSVWrite.csv", row.names = FALSE)


Output:
Above code creates a new file and redirects the output. The contents of the file is shown below after executing the code-


Previous Article
Next Article

Similar Reads

Is the R programming environment capable of handling unstructured data?
Yes, the R programming environment is capable of handling unstructured data. R provides a wide range of packages and tools specifically designed for processing, analyzing, and visualizing unstructured data, such as text, images, and social media feeds. While traditionally known for its strengths in statistical analysis and structured data, R has ev
2 min read
Handling Errors in R Programming
Error Handling is a process in which we deal with unwanted or anomalous errors which may cause abnormal termination of the program during its execution. In R Programming, there are basically two ways in which we can implement an error handling mechanism. Either we can directly call the functions like stop() or warning(), or we can use the error opt
3 min read
Handling Missing Values in R Programming
As the name indicates, Missing values are those elements that are not known. NA or NaN are reserved words that indicate a missing value in R Programming language for q arithmetical operations that are undefined. R - Handling Missing ValuesMissing values are practical in life. For example, some cells in spreadsheets are empty. If an insensible or im
5 min read
File Handling in R Programming
In R Programming, handling of files such as reading and writing files can be done by using in-built functions present in R base package. In this article, let us discuss reading and writing of CSV files, creating a file, renaming a file, check the existence of the file, listing all files in the working directory, copying files and creating directori
4 min read
Condition Handling in R Programming
Decision handling or Condition handling is an important point in any programming language. Most of the use cases result in either positive or negative results. Sometimes there is the possibility of condition checking of more than one possibility and it lies with n number of possibilities. In this article let's discuss how condition handling works i
5 min read
How to Implement Error Handling in R Programming
Error handling is a crucial aspect of programming that allows to identify, and gracefully manage errors or exceptions that may occur during the execution of code. In R Programming Language, effective error handling can enhance the reliability of scripts and applications. What are Errors in R?An error refers to a condition that occurs when the execu
6 min read
Handling Inconsistent Data
Handling inconsistent data in R is a crucial step in data preprocessing and cleaning. Inconsistent data can include missing values, outliers, errors, and inconsistencies in formats. In R Programming Language Properly addressing these issues ensures that your data is reliable and suitable for analysis. Here are common techniques for handling inconsi
6 min read
Handling Missing Values in Time Series Data
Handling missing values in time series data in R is a crucial step in the data preprocessing phase. Time series data often contains gaps or missing observations due to various reasons such as sensor malfunctions, human errors, or other external factors. In R Programming Language dealing with missing values appropriately is essential to ensure the a
5 min read
Data Wrangling in R Programming - Data Transformation
A dataset can be presented in many different ways to the world. Let us look at one of the most essential and fundamental distinctions, whether a dataset is wide or long. The difference between wide and long datasets condenses to whether we prefer to have more rows in our dataset or more columns. A dataset that spotlights on putting additional data
3 min read
Convert an Object to Data Frame in R Programming - as.data.frame() Function
as.data.frame() function in R Programming Language is used to convert an object to data frame. These objects can be Vectors, Lists, Matrices, and Factors. Syntax: as.data.frame(object) Parameters: object: Vector, Matrix, factor, or data frameR - as.data.frame() Function ExampleExample 1: Basic example of as.data.frame() Function in R C/C++ Code # R
2 min read
Check if the Object is a Data Frame in R Programming - is.data.frame() Function
is.data.frame() function in R Language is used to return TRUE if the specified data type is a data frame else return FALSE. R data.frame is a powerful data type, especially when processing table (.csv). It can store the data as row and columns according to the table. Syntax: is.data.frame(x) Parameters: x: specified data.frame Example 1: # R progra
1 min read
Convert a Data Frame into a Numeric Matrix in R Programming - data.matrix() Function
data.matrix() function in R Language is used to create a matrix by converting all the values of a Data Frame into numeric mode and then binding them as a matrix. Syntax: data.matrix(df) Parameters: df: Data frame to be converted. Example 1: # R program to convert a data frame # into a numeric matrix # Creating a dataframe df1 = data.frame( "Na
2 min read
Modify Data of a Data Frame with an Expression in R Programming - with() Function
with() function in R Language is used to modify data of a data frame by evaluating an expression within the arguments of the function. Syntax: with(x, expr) Parameters: x: Data frame expr: Expression to modify data Example 1: # R program to modify data of an object # Calling predefined data set BOD # Calling with() function with(BOD, {BOD$demand
1 min read
Generate a set of Sample data from a Data set in R Programming - sample() Function
sample() function in R Language creates random sample based on the parameters provided in the function call. It takes either a vector or a positive integer as the object in the function parameter. Syntax: sample(x, size, replace) Parameters: x: indicates either vector or a positive integer or data frame size: indicates size of sample to be taken re
2 min read
data.table vs data.frame in R Programming
data.table in R is an enhanced version of the data.frame. Due to its speed of execution and the less code to type it became popular in R. The purpose of data.table is to create tabular data same as a data frame but the syntax varies. In the below example let we can see the syntax for the data table: C/C++ Code DataTable = data.table(name = c("
3 min read
Is it Mandatory to Learn R Programming Language for Becoming a Master in Data Science and Big Data?
It is not mandatory to learn R programming to become a master in data science and big data, but it is highly beneficial. R is one of the leading languages for statistical analysis and has powerful tools for data visualization, which are crucial skills in data science. However, proficiency in other languages like Python can also provide a comprehens
3 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
Data Reshaping in R Programming
Generally, in R Programming Language, data processing is done by taking data as input from a data frame where the data is organized into rows and columns. Data frames are mostly used since extracting data is much simpler and hence easier. But sometimes we need to reshape the format of the data frame from the one we receive. Hence, in R, we can spli
5 min read
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
Comparing values of data frames in R Programming - all_equal() Function
all_equal() function in R Language is used to compare the values between dataframes. Syntax: all_equal(target, current, check.attributes, check.names) Parameters: target: object to comparecurrent: object to be compared withcheck.attributes: If attributes of both be comparedcheck.names: If names be comparedR - compare values of data frames Example 1
2 min read
Convert type of data object in R Programming - type.convert() Function
type.convert() function in R Language is used to compute the data type of a particular data object. It can convert data object to logical, integer, numeric, or factor. Syntax: type.convert(x) Parameter: x: It can be a vector matrix or an array Example 1: Apply type.convert to vector of numbers # R program to illustrate # type.convert to vector of n
2 min read
Create Matrix and Data Frame from Lists in R Programming
In R programming, there 5 basic objects. Lists are the objects that can contain heterogeneous types of elements, unlike vectors. Matrices can contain the same type of elements or homogeneous elements. On the other hand, data frames are similar to matrices but have an advantage over matrices to keep heterogeneous elements. In this article, we'll lea
3 min read
Check if Object is of the Character Data type in R Programming - is.character() Function
is.character() Function in R Language is used to check if the object is of the form of a string/character or not. It will return true if any element of the object is of the character data type. Syntax: is.character(Object) Parameter: Object: It could be an array, list, vector, etc. Example 1: # R Program to illustrate # the use of is.character func
1 min read
Get Transpose of a Matrix or Data Frame in R Programming - t() Function
t() function in R Language is used to calculate transpose of a matrix or Data Frame. Syntax: t(x) Parameters: x: matrix or data frame Example 1: # R program to illustrate # t function # Getting R Biochemical Oxygen Demand Dataset BOD # Calling t() function t(BOD) Output: Time demand 1 1 8.3 2 2 10.3 3 3 19.0 4 4 16.0 5 5 15.6 6 7 19.8 [, 1] [, 2] [
1 min read
Compute the Hyperbolic arctangent of numeric data in R Programming - atanh() Function
atanh() function in R Language is used to compute the hyperbolic arctangent of numeric data. Syntax: atanh(x) Parameters: x: Numeric value, array or vector. Example 1: # R program to illustrate # atanh function # Calling atanh() function over # different numbers atanh(0) atanh(1) atanh(0.9) atanh(-0.8) Output: [1] 0 [1] Inf [1] 1.472219 [1] -1.0986
1 min read
Compute the Hyperbolic arcsine of numeric data in R Programming – asinh() Function
asinh() function in R Language is used to compute the hyperbolic arcsine of numeric data. Syntax:asinh(x) Parameters: x: Numeric value, array or vector Example 1: # R program to illustrate # asinh function # Calling asinh() function over # different numbers asinh(0) asinh(1) Output: [1] 0 [1] 0.8813736 Example 2: # R program to illustrate # asinh f
1 min read
Compute the Hyperbolic arccosine of numeric data in R Programming – acosh() Function
acosh() function in R Language is used to compute the hyperbolic arccosine of numeric data. Syntax:acosh(x) Parameters: x: Numeric value, array or vector Example 1: # R program to illustrate # acosh function # Calling acosh() function over # different numbers acosh(0) acosh(1) Output: [1] NaN [1] 0 Example 2: # R program to illustrate # acosh funct
1 min read
Getting class of different data types in R Programming - class() Function
class() function in R Language is used to return the class of data used as the arguments. Syntax: class(x) Parameters: x: specified data Example 1: # R program to illustrate # class function # Specifying "Biochemical oxygen demand" # data set x <- BOD x # Calling class() function class(x) Output: Time demand 1 1 8.3 2 2 10.3 3 3 19.0 4
1 min read
Getting type of different data types in R Programming - typeof() Function
typeof() function in R Language is used to return the types of data used as the arguments. Syntax: typeof(x) Parameters: x: specified data Example 1: # R program to illustrate # typeof function # Specifying "Biochemical oxygen demand" # data set x <- BOD x # Calling typeof() function typeof(x) Output: Time demand 1 1 8.3 2 2 10.3 3 3 1
1 min read
Merge Two Data Frames by common Columns in R Programming - merge() Function
merge() function in R Language is used to merge two data frames by common columns. Syntax: merge(arg1, arg2, by.x, by.y) Parameters: arg1 and arg2: Data frames to be merged by.x: Common argument of first data frame by.y: Common argument of second data frame Example 1: # R program to merge two data frames # Creating data frames df1 <- data.frame(
1 min read
Article Tags :
three90RightbarBannerImg