Skip to content
Related Articles

Related Articles

Improve Article

Read text File with Space as Delimiter in R

  • Last Updated : 23 Sep, 2021
Geek Week

In this article, we will discuss how to read a text file with spaces as delimiters in R programming language.

Base R allows us to read and access the content within the text files with any number of characters as the delimiter. 

File in use: 

The read.table() method in R can be used to read data from a text file into the data.table or a similar R object. In case the file is located within the same directory, the file-name is specified, else the complete path to the file is given in the workspace. Also, the header is an optional parameter, if TRUE, the header is read into the workspace else, omitted. 



Syntax:

read.table( path-of-the-file, header = T)

Example: Read TXT file with spaces as a delimiter

R




# reading data from the text file
file_path <- "r_content.txt"
  
data_table <- read.table(file_path, 
                   header = TRUE)
  
print("Contents of the text file")
print(data_table)

Output:

[1] "Contents of the text file" 
col1 col2 col3 
1    1    3    A 
2    3    5    B 
3    6    8    C 
4    8   12    D

The “sep” argument is used to specify the delimiter of the text file cell values. The “sep” argument of the data.table can also be used to read a text file containing data with single or multiple spaces as delimiters. The sep = “” is used to refer to any length whitespace as being the delimiter.

Syntax:

read.table(filepath, sep, header=T, na.strings, stringAsFactors)

Example: Read TXT file with spaces as a delimiter

R




# reading data from the text file
file_path <- "r_content.txt"
  
data_table <- read.table(file_path, sep = "" , header = T ,
                                  na.strings =""
                         stringsAsFactors= F)
  
print("Contents of the text file")
print(data_table)

Output:

[1] "Contents of the text file" 
col1 col2 col3 
1    1    3    A 
2    3    5    B 
3    6    8    C 
4    8   12    D



My Personal Notes arrow_drop_up
Recommended Articles
Page :