How To Import Data from a File in R Programming
The collection of facts is known as data. Data can be in different forms. To analyze data using R, data should be first imported in R which can in different formats like txt, CSV, or any other delimiter separated files. After import data then manipulate, analyze, and report it.
Importing Data from a Text File
We can easily import or read .txt file using basic R function
read.table() is used to read a file in table format. This function is easy to use and flexible.
# read data stored in .txt file x<-read.table("file_name.txt", header=TRUE/FALSE)
V1 V2 V3 1 100 a1 b1 2 200 a2 b2 3 300 a3 b3
X100 a1 b1 1 200 a2 b2 2 300 a3 b3
If the header argument is set at TRUE, which read the column names if they exist in the file.
Importing Data from a CSV file
CSV(Comma Separated Values) file contains list of data which separated from comma(, ) .To import csv file R uses
read.csv2() function. Both function are almost same as to the
# import csv file using read.csv() x <- read.csv("file_name.txt")
X V1 V2 V3 1 1 100 a1 b1 2 2 200 a2 b2 3 3 300 a3 b3
# import csv file using read.table() x <- read.table("file_name.txt", header = TRUE, sep="")
Col1.Col2.Col3 1 100, a1, b1 2 200, a2, b2 3 300, a3, b3
Importing Data from a delimited file
R has a function
read.delim() to read delimited file in to list. File is by default separated by tab which is represented by sep="", that separated can be comma(, ), dollar symbol($) etc.
# import delimited file x <- read.delim("file_name.txt", sep="", header=TRUE)
X.V1.V2.V3 1 1, 100, a1, b1 2 2, 200, a2, b2 3 3, 300, a3, b3  "list
V1 1, V1, V2, V3 2 1, 100, a1, b1 3 2, 200, a2, b2 4 3, 300, a3, b3  "list