Importing Data in R

Importing data in R programming means that we can read data from external files, write data to external files, and can access those files from outside the R environment. File formats like CSV, XML, xlsx, JSON, and web data can be imported into the R environment to read the data and perform data analysis, and also the data present in the R environment can be stored in external files in the same file formats.

We have the perfect professional R Programming Training Course for you!

Check this Intellipaat video on R Programming:

Before going further in this importing data in R tutorial, let’s have a quick glance at the topics that we will cover in this tutorial:

Reading CSV Files

CSV (Comma Separated Values) is a text file in which the values in columns are separated by a comma.
For importing data in the R programming environment, we have to set our working directory with the setwd() function.
For example:

setwd("C:/Users/intellipaat/Desktop/BLOG/files")

To read a csv file, we use the in-built function read.csv() that outputs the data from the file as a data frame.

Get familiar with the top R Programming Interview Questions to get a head start in your career!

For example:

read.data <- read.csv("file1.csv")
print(read.data)

Output:

Sl. No.empidempnameempdeptempsalaryempstart_date
11SamIT2500003-09-2005
22RobHR3000003-05-2005
33MaxMarketing2900005-06-2007
44JohnR&D3500001-03-1999
55GaryFinance3200005-09-2000
66AlexTech2000009-05-2005
77IvarSales3600004-04-1999
88RobertFinance3400006-08-2008

Analyzing a CSV File

#To print number of columns
print(ncol(read.data))

Output:

[1] 5
#To print number of rows
print(nrow(read.data))

Output:

[1] 8
#To print the range of salary packages
range.sal <- range(read.data$empsalary)
print(range.sal)

Output:

[1] 20000 36000
#To print the details of a person with the highest salary, we use the subset() function to extract variables and observations
max.sal <- subset(read.data, empsalary == max(empsalary))
print(max.sal)

Output:

Sl. No.empidempnameempdeptempsalaryempstart_date
77IvarSales3600004-04-1999

 

#To print the details of all people working in Finance department
fin.per <- subset(read.data, empdept == “Finance”)
print(fin.per)

Output:

Sl. No.empidempnameempdeptempsalaryempstart_date
55GaryFinance3600005-09-2000
88RobertFinance3400006-08-2008

For the best of career growth, check out Intellipaat’s R Programming Training in Sydney and get certified!

Writing to a CSV File

To write data to a CSV file, we use the write.csv() function. The output file is stored in the working directory of our R programming environment.
For example:

#To print the details of people having salary between 30000 and 40000 and store the results in a new file
per.sal <- subset(read.data, empsalary >= "30000" & empsalary <= "40000")
print(per.sal)

Output:

empidempnameempdeptempsalaryempstart_date
22RobHR3000003-05-2002
44JohnR&D3500001-03-1999
55GaryFinance3200005-09-2000
77IvarSales3600004-04-1999
88RobertFinance3400006-08-2008

 

# Writing data into a new CSV file
write.csv(per.sal,"output.csv")
new.data <- read.csv("output.csv")
print(new.data)

Output:

 xempidempnameempdeptempsalaryempstart_date
122RobHR3000003-05-2002
244JohnR&D3500001-03-1999
355GaryFinance3200005-09-2000
477IvarSales3600004-04-1999
588RobertFinance3400006-08-2008

 

# To exclude the extra column X from the above file
write.csv(per.sal,"output.csv", row.names = FALSE)
new.data <- read.csv("output.csv")
print(new.data)
 empidempnameempdeptempsalaryempstart_date
12RobHR3000003-05-2002
24JohnR&D3500001-03-1999
35GaryFinance3200005-09-2000
47IvarSales3600004-04-1999
58RobertFinance3400006-08-2008

Reading XML Files

XML (Extensible Markup Language) file shares both data and file format on the web, and elsewhere, using the ASCII text. Like an html file, it also contains markup tags, but the tags in an XML file describe the meaning of the data contained in the file rather than the structure of the page.
For importing data in R from XML files, we need to install the XML package, which can be done as follows:

install.packages("XML")

To read XML files, we use the in-built function xmlParse().
For example:

#To load required xml package to read XML files
library("XML") 
#To load other required packages
library("methods") 
#To give the input file name to the function
newfile <- xmlParse(file = "file.xml") 
print(newfile)

Output:

<?xml version="1.0"?>
<RECORDS>
<EMPLOYEE>
<ID>1</ID>
<NAME>Sam</NAME>
<SALARY>32000</SALARY>
<STARTDATE>1/1/2001</STARTDATE>
<DEPT>HR</DEPT>
</EMPLOYEE>
<EMPLOYEE>
<ID>2</ID>
<NAME>Rob</NAME>
<SALARY>36000</SALARY>
<STARTDATE>9/3/2006</STARTDATE>
<DEPT>IT</DEPT>
</EMPLOYEE>
<EMPLOYEE>
<ID>3</ID>
<NAME>Max</NAME>
<SALARY>42000</SALARY>
<STARTDATE>1/5/2011</STARTDATE>
<DEPT>Sales</DEPT>
</EMPLOYEE>
<EMPLOYEE>
<ID>4</ID>
<NAME>Ivar</NAME>
<SALARY>50000</SALARY>
<STARTDATE>25/1/2001</STARTDATE>
<DEPT>Tech</DEPT>
</EMPLOYEE>
<EMPLOYEE>
<ID>5</ID>
<NAME>Robert</NAME>
<SALARY>25000</SALARY>
<STARTDATE>13/7/2015</STARTDATE>
<DEPT>Sales</DEPT>
</EMPLOYEE>
<EMPLOYEE>
<ID>6</ID>
<NAME>Leon</NAME>
<SALARY>57000</SALARY>
<STARTDATE>5/1/2000</STARTDATE>
<DEPT>IT</DEPT>
</EMPLOYEE>
<EMPLOYEE>
<ID>7</ID>
<NAME>Samuel</NAME>
<SALARY>45000</SALARY>
<STARTDATE>27/3/2003</STARTDATE>
<DEPT>Operations</DEPT>
</EMPLOYEE>
<EMPLOYEE>
<ID>8</ID>
<NAME>Jack</NAME>
<SALARY>24000</SALARY>
<STARTDATE>6/1/2016</STARTDATE>
<DEPT>Sales</DEPT>
</EMPLOYEE>
</RECORDS>
#To get the root node of xml file
rootnode <- xmlRoot(newfile)
#To get the number of nodes in the
rootrootsize <- xmlSize(rootnode)
print(rootsize)

Output:      [1] 8

#To print a specific node
print(rootnode[1])

Output:

$EMPLOYEE
<EMPLOYEE>
<ID>1</ID>
<NAME>Sam</NAME>
<SALARY>32000</SALARY>
<STARTDATE>1/1/2001</STARTDATE>
<DEPT>HR</DEPT>
</EMPLOYEE>
attr(,"class")
[1] "XMLInternalNodeList" "XMLNodeList"
#To print elements of a particular node
print(rootnode[[1]][[1]])
print(rootnode[[1]][[3]])
print(rootnode[[1]][[5]])

Output:

<ID>1</ID>
<SALARY>32000</SALARY>
<DEPT>HR</DEPT>

Converting an XML to a Data Frame            

To perform data analysis effectively after importing data in R, we convert the data in an XML file to a Data Frame. After converting, we can perform data manipulation and other operations as performed in a data frame.
For example:

library("XML")
library("methods")
#To convert the data in xml file to a data frame
xmldataframe <- xmlToDataFrame("file.xml")
print(xmldataframe)

Output:

 IDNAMESALARYSTARTDATEDEPT
11Sam3200001/01/2001HR
22Rob3600009/03/2006IT
33Max4200001/05/2011Sales
44Ivar5000025/01/2001Tech
55Robert2500013/07/2015Sales
66Leon5700005/01/2000IT
77Samuel4500027/03/2003Operations
88Jack2400006/01/2016Sales

Reading JSON Files

JSON (JavaScript Object Notation) file is used to exchange data between a web application and a server. They are text-based human-readable files and can be edited by a normal text editor.
Importing data in R from a JSON file requires the rjson package that can be installed as follows:

install.packages("rjson")

Now to read json files, we use the in-built function from JSON() which stores the data as a list.
For example:

#To load rjson package
library("rjson")
#To give the file name to the function
newfile <- fromJSON(file = "file1.json")
#To print the file
print(newfile)

Output:

$ID
[1] "1" "2" "3" "4" "5" "6" "7" "8"
$Name
[1] "Sam"    "Rob"    "Max"    "Robert" "Ivar"   "Leon"   "Samuel" "Ivar"
$Salary
[1] "32000" "27000" "35000" "25000" "37000" "41000" "36000" "51000"
$StartDate
[1] "1/1/2001"  "9/3/2003"  "1/5/2004"  "14/11/2007" "13/7/2015" "4/3/2007"
[7] "27/3/2013"  "25/7/2000"
$Dept
[1] "IT"         "HR"         "Tech"       "HR"         "Sales"      "HR"
[7] "Operations" "IT"

Converting a JSON File to a Data Frame
To convert JSON file to a Data Frame, we use the as.data.frame() function.
For example:

library("rjson")
newfile <- fromJSON(file = "file1.json")
#To convert a JSON file to a data frame
jsondataframe <- as.data.frame(newfile)
print(jsondataframe)

Output:

 IDNAMESALARYSTARTDATEDEPT
11Sam3200001/01/2001IT
22Rob2700009/03/2003HR
33Max3500001/05/2004Tech
44Ivar2500014/11/2007HR
55Robert3700013/07/2015Sales
66Leon4100004/03/2007HR
77Samuel3600027/03/2013Operations
88Jack5100025/07/2000IT

Reading Excel Files

Microsoft Excel is a very popular spreadsheet program that stores data in xls and xlsx format. We can read and write data, from and to Excel files using the readxl package in R.

To install the readxl package, run the following command
install.packages("readxl")
For importing data in R programming from an excel file, we use the read_excel() function that stores it as a data frame.
newfile <- read_excel("sheet1.xlsx)
print(newfile)

Output:

 IDNAMEDEPTSALARYAGE
11SAMSALES3200035
22ROBHR3600023
33MACIT3700040
44IVARIT2500037
55MAXR&D3000022
66ROBERTHR2700032
77SAMUELFINANCE5000041
88RAGNARSALES4500029

Reading HTML Tables

To read HTML tables from websites and retrieve data from them, we use the XML and RCurl packages in R programming.
To install XML and RCurl packages, run the following command:

install.packages("XML")
install.packages("RCurl")

To load the packages, run the following command:

library("XML")
library("RCurl")

For example, we will fetch the ‘Ease of Doing Business Index’ table from a URL using the readHTMLTable() function which stores it as a Data Frame.

#To fetch a table from any website paste the url
url <- "https://en.wikipedia.org/wiki/Ease_of_doing_business_index#Ranking"
tabs <- getURL(url)
#To fetch the first table,if the webpage has more than one table, we use which = 1
tabs <- readHTMLTable(tabs,which = 1, stringsAsFactors = F)
head(tabs)

Output:

V1V2V3V4V5V6V7V8V9V10V11V12V13
1ClassificationJurisdiction20192018201720162015201420132012201120102009
2Very EasyNew Zealand11122333322
3Very EasySingapore22211111111
4Very EasyDenmark33334555665
5Very EasyHong Kong45443222234
6Very EasySouth Korea54555788161923
V14V15V16
1200820072006
2221
3112
4578
5457
6302327

Have you got more queries? Come to our R Programming Community and get them clarified today!

We use the str() function to analyze the structure of the data frame.
For example:

str(tabs)

Output:

'data.frame':  191 obs. of  16 variables:
$ V1 : chr  "Classification" "Very Easy" "Very Easy" "Very Easy" ...
$ V2 : chr  "Jurisdiction" "New Zealand" "Singapore" "Denmark" ...
$ V3 : chr  "2019" "1" "2" "3" ...
$ V4 : chr  "2018" "1" "2" "3" ...
$ V5 : chr  "2017" "1" "2" "3" ...
$ V6 : chr  "2016" "2" "1" "3" ...
$ V7 : chr  "2015" "2" "1" "4" ...
$ V8 : chr  "2014" "3" "1" "5" ...
$ V9 : chr  "2013" "3" "1" "5" ...
$ V10: chr  "2012" "3" "1" "5" ...
$ V11: chr  "2011" "3" "1" "6" ...
$ V12: chr  "2010" "2" "1" "6" ...
$ V13: chr  "2009" "2" "1" "5" ...
$ V14: chr  "2008" "2" "1" "5" ...
$ V15: chr  "2007" "2" "1" "7" ...
$ V16: chr  "2006" "1" "2" "8" ...
#To print rows from 5 to 10 and columns from 1 to 8
T1 <- tabs[5:10, 1:8]
head(T1)

Output:

V1V2V3V4V5V6V7V8
5Very EasyHong Kong454532
6Very EasySouth Korea545457
7Very EasyGeorgia691624158
8Very EasyNorway786969
9Very EasyUnited States868774
10Very EasyUnited Kingdom9776810

 

#To find the position of India in the Table
T1 <- subset(tabs,tabs$V2 == "India")
head(T1)

Output:

V1V2V3V4V5V6V7V8V9V10V11V12V13V14V15V16
78EasyIndia77100130130142134132132134133122120134116

In this tutorial, we learned what importing data in R is, how to read files in different formats in R, and how to convert data from files to data frames for efficient data manipulation. In the next session, we are going to talk about data manipulation in R.

Wish to get certified in R! Learn R from top R experts and excel in your career with Intellipaat’s R Programming certification!

Recommended Videos

Leave a Reply

Your email address will not be published. Required fields are marked *