The Wayback Machine - https://web.archive.org/web/20240815231624/https://www.geeksforgeeks.org/importing-data-in-r-script/
Open In App

Importing Data in R Script

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

We can read external datasets and operate with them in our R environment by importing data into an R script. R offers a number of functions for importing data from various file formats.

In this article, we are going to see how to Import data in R Programming Language.

Importing Data in R

First, let’s consider a data set that we can use for the demonstration. For this demonstration, we will use two examples of a single dataset, one in .csv form and another .txt

Importing Data in R ScriptGeeksforgeeks

Importing Data in R Script

Reading a Comma-Separated Value(CSV) File

Method 1: Using read.csv() Function Read CSV Files into R

The function has two parameters: 

  • file.choose(): It opens a menu to choose a CSV file from the desktop.
  • header: It is to indicate whether the first row of the dataset is a variable name or not. Apply T/True if the variable name is present else put F/False.

Example: 

R




# import and store the dataset in data1
data1 <- read.csv(file.choose(), header=T)
 
# display the data
data1


Output: 

Importing Data in R ScriptGeeksforgeeks

Importing Data in R Script

Method 2: Using read.table() Function

This function specifies how the dataset is separated, in this case we take sep=”, “ as an argument.

Example: 

R




# import and store the dataset in data2
data2 <- read.table(file.choose(), header=T, sep=", ")
 
# display data
data2


Output: 

Importing Data in R ScriptGeeksforgeeks

Importing Data in R Script

Reading a Tab-Delimited(txt) File in R Programming Language

Method 1: Using read.delim() Function

The function has two parameters: 

  • file.choose(): It opens a menu to choose a csv file from the desktop.
  • header: It is to indicate whether the first row of the dataset is a variable name or not. Apply T/True if the variable name is present else put F/False.

Example: 

R




# import and store the dataset in data3
data3 <- read.delim(file.choose(), header=T)
 
# display the data
data3


Output: 

Importing Data in R ScriptGeeksforgeeks

Importing Data in R Script

Method 2: Using read.table() Function

This function specifies how the dataset is separated, in this case we take sep=”\t” as the argument.

Example: 

R




# import and store the dataset in data4
data4 <- read.table(file.choose(), header=T, sep="\t")
 
# display the data
data4


Output: 

Importing Data in R Script

Using R-Studio

Here we are going to import data through R studio with the following steps.

Steps: 

  • From the Environment tab click on the Import Dataset Menu.

Importing Data in R Script

  • Select the file extension from the option.

Importing Data in R Script

  • In the third step, a pop-up box will appear, either enter the file name or browse the desktop.
  • The selected file will be displayed on a new window with its dimensions.
  • In order to see the output on the console, type the filename.

Read JSON Files Into R

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:

  • Install and load the rjson package in R console
  • Create a JSON file
  • Reading data from JSON file
  • Write into JSON file
  • Converting the JSON data into Dataframes
  • Working with URLs

JSON file for demonstration:

{ 
   "ID":["1","2","3","4","5"],
   "Name":["Mithuna","Tanushree","Parnasha","Arjun","Pankaj"],
   "Salary":["722.5","815.2","1611","2829","843.25"],
   "StartDate":["6/17/2014","1/1/2012","11/15/2014","9/23/2013","5/21/2013"],
   "Dept":["IT","IT","HR","Operations","Finance"]
}

Code:

R




# Read a JSON file
 
# Load the package required to read JSON files.
library("rjson")
 
# Give the input file name to the function.
result <- fromJSON(file = "E:\\example.json")
 
# Print the result.
print(result)


Output:

$ID
[1] "1" "2" "3" "4" "5"

$Name
[1] "Mithuna"   "Tanushree" "Parnasha"  "Arjun"     "Pankaj"

$Salary
[1] "722.5"  "815.2"  "1611"   "2829"   "843.25"

$StartDate
[1] "6/17/2014"  "1/1/2012"   "11/15/2014" "9/23/2013"  "5/21/2013"

$Dept
[1] "IT"         "IT"         "HR"         "Operations" "Finance"


Previous Article
Next Article

Similar Reads

How to get the path of current script in R ?
In this article, we will see how to determine the path of the current script in R Programming Language. Method 1: Traditional method If we want to check the current directory of the R script, we can use getwd( ) function. For getwd( ), no need to pass any parameters. If we run this function we will get the current working directory or current path
2 min read
How to Read Command Line Parameters from an R Script?
Reading command line parameters in an R script is essential for creating flexible and reusable scripts that can handle different inputs without modifying the code. This is particularly useful for automation and batch-processing tasks. This article will guide you through the process of reading command line parameters in an R Programming Language scr
3 min read
Why is R Programming called a Shell Script?
Answer: R programming is sometimes referred to as a shell script because it can be used in a similar way to traditional shell scripts for automating tasks, running commands, and managing workflows in a Unix-like environment. However, it’s important to clarify that R itself is not inherently a shell script language; rather, it can function like one
2 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( &quot;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(&quot;
3 min read
Article Tags :
three90RightbarBannerImg