Skip to content
Related Articles

Related Articles

Improve Article

How To Import Data from a File in R Programming

  • Last Updated : 01 Jun, 2020

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(). read.table() is used to read a file in table format. This function is easy to use and flexible.
Syntax:

# read data stored in .txt file
x<-read.table("file_name.txt", header=TRUE/FALSE)

Example 1:




# Simple R program to read txt file
x<-read.table("D://Data//myfile.txt", header=FALSE)
  
# print x
print(x)

Output:

   V1 V2 V3
1 100 a1 b1
2 200 a2 b2
3 300 a3 b3

Example 2:






# Simple R program to read txt file
x<-read.table("D://Data//myfile.txt", header=TRUE)
  
# print x
print(x)

Output:

  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.csv() or read.csv2() function. Both function are almost same as to the read.table() function.
Syntax:

# import csv file using read.csv()
x <- read.csv("file_name.txt")




# Simple R program to read csv file
x <- read.csv("D://Datas//myfile.csv")
  
# print x
print(x)

Output:

  X  V1 V2 V3
1 1 100 a1 b1
2 2 200 a2 b2
3 3 300 a3 b3

Syntax:

# import csv file using read.table()
x <- read.table("file_name.txt", header = TRUE, sep="")




# simple R program to read csv file using read.table()
x <- read.csv2("D://Data//myfile.csv", header = TRUE, sep=", ")
  
# print x
print(x)

Output:

  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.
Syntax:

# import delimited file
x <- read.delim("file_name.txt", sep="", header=TRUE)

Example 1:




x <- read.delim("D://Data//myfile.csv", sep="|", header=TRUE)
  
# print x
print(x)
  
# print type of x
typeof(x)

Output:

X.V1.V2.V3
1 1, 100, a1, b1
2 2, 200, a2, b2
3 3, 300, a3, b3


[1] "list

Example 2:




x <- read.delim("D://Data//myfile.csv", sep="|", header=FALSE)
  
# print x
print(x)
  
# print type of x
typeof(x)

Output:

        V1
1, V1, V2, V3
2 1, 100, a1, b1
3 2, 200, a2, b2
4 3, 300, a3, b3

[1] "list




My Personal Notes arrow_drop_up
Recommended Articles
Page :