Import Data from a File in detail
Data is a collection of facts and can exist in multiple formats. To analyze data using the R programming language, it first needs to be imported. R allows importing data from various file types such as text files, CSV, and other delimiter-separated files. Once imported, users can manipulate, analyze, and generate reports from the data.
Importing Data from Files into R
This guide demonstrates how to import different file formats into R programming.
Importing CSV Files
Method 1: Using read.csv()
The read.csv() function is a straightforward method for importing CSV files.
read.csv(file_path, header = TRUE, sep = ",")
Arguments:
- file_path: The file’s location.
- header: TRUE (default) to indicate column headings.
- sep: The separator for values in each row (default is a comma ,).
Example:
# Specify file path
file_path <- "data.csv"
# Read the CSV file
content <- read.csv(file_path)
# Print file contents
print(content)
Output:
ID Name Role Age
1 1 Alex Dev 30
2 2 Sam QA 25
3 3 Emma HR 28
Method 2: Using read.table()
Another way to import CSV files is by using read.table().
# Import CSV using read.table()
data <- read.table("C://data//records.csv", header = TRUE, sep = ",")
# Print file contents
print(data)
Output:
Col1 Col2 Col3
1 101 A1 B1
2 202 A2 B2
3 303 A3 B3
Importing Data from a Text File
read.table() can also be used for importing text files.
Syntax:
read.table("file.txt", header = TRUE/FALSE)
Example:
# Read text file
data <- read.table("C://data//records.txt", header = FALSE)
# Print file contents
print(data)
Output:
V1 V2 V3
1 200 A1 B1
2 300 A2 B2
3 400 A3 B3
Importing Data from a Delimited File
The read.delim() function is used to import delimited files, where values are separated by specific symbols such as |, $, or ,.
Syntax:
read.delim("file.txt", sep="|", header=TRUE)
Example:
# Read a delimited file
data <- read.delim("C://data//info.txt", sep="|", header=TRUE)
# Print file contents
print(data)
Output:
$ID
[1] "101" "102" "103"
$Name
[1] "John" "Lily" "Raj"
$Salary
[1] "1500" "2000" "2500"
Importing XML Files
To import XML files, use the XML package.
XML File Sample:
<RECORDS>
<EMPLOYEE>
<ID>1</ID>
<NAME>Adam</NAME>
<SALARY>5000</SALARY>
</EMPLOYEE>
<EMPLOYEE>
<ID>2</ID>
<NAME>Sophia</NAME>
<SALARY>6000</SALARY>
</EMPLOYEE>
</RECORDS>
Example:
# Load XML package
library("XML")
# Parse XML file
data <- xmlParse(file = "C://data//employees.xml")
# Print parsed data
print(data)
Output:
1 Adam 5000
2 Sophia 6000
Importing SPSS Files
SPSS .sav files can be imported using the haven package.
Syntax:
read_sav("file.sav")
Example:
# Load haven package
library("haven")
# Read SPSS file
data <- read_sav("C://data//survey.sav")
# Print data
print(data)
Output:
ID Age Response Score
1 1 23 Agree 4.5
2 2 30 Neutral 3.0
3 3 27 Disagree 2.5
Leave a Reply