Read TXT File with Spaces as Delimiter in R (Example)
In this tutorial you’ll learn how to import a text file with spaces as separator in the R programming language.
The article will consist of this information:
Let’s get started…
Creating Example Data
For this example, I have created a TXT file that looks as shown in the screenshot below:
Note that between some values there is one space as separator and between other values there are multiple spaces as separator.
Example: Reading Text File with Multiple Spaces as Delimiter
The following code shows how to import a text file with a different number of spaces as delimiter using the read.table function.
Surprisingly, the answer is quite easy in R – Just don’t specify any separator within the read.table function. The R programming language knows by default how to handle multiple spaces.
Have a look at the following R code and its output:
data <- read.table("my file.txt", # Read TXT file header = TRUE) data # Print data in RStudio
The previous table shows that our example data consists of four rows and three columns. The multiple spaces did not cause any problems when importing the data even though we didn’t specify the sep argument of the read.table function.
Video & Further Resources
Do you need more explanations on the topics of this article? Then you might want to have a look at the following video of my YouTube channel. In the video instruction, I show the R programming codes of this article:
Please accept YouTube cookies to play this video. By accepting you will be accessing content from YouTube, a service provided by an external third party.
If you accept this notice, your choice will be saved and the page will refresh.
In addition, you may want to have a look at the other R programming tutorials on this homepage:
- Read All Worksheets of Excel File into List
- Read Fixed Width Text File in R
- Import Text File as Single Character String
- sink Function in R
- All R Programming Examples
To summarize: In this tutorial, I have illustrated how to read a TXT file with multiple spaces as delimiter in R programming. In case you have further comments or questions, tell me about it in the comments below.