Reading Text (*.txt) Files

We can import data that is already saved (available) in a file created in a text (*.txt) files, MS-Excel, SPSS, or some other software. Before importing a data stored in a file (that is, reading test (*.txt) files), one should be clear and understand the following:

  1. Usually, data produced from spreadsheets reserved the first row as header (name of variables), while the first column is used to identify the sampling unit (observation number).
  2. Avoid names, the value of fields with blank spaces, each word may be interpreted as a separate variable, resulting in errors.
  3. To concatenate words, use a full stop (.) instead of space between words.
  4. Name variables with short or as abbreviated names.
  5. Try to avoid using names of variables that contains symbols such as ?, $, %, ^, *, (, ), – , #, <, >, /, |, ,\, [, ], {, and }.
  6. Delete comments if you have made in your excel file.
  7. Make sure missing values in your dataset are indicated with NA.

Preparing you R workspace

Before importing data in R, it is better to delete all objects using the following line of code

rm(list = ls() )

The rm( ) function “remove objects from a specified environment”. Since no argument to ls( ) function is provided, datasets and user-defined functions will be deleted.

Confirm your working directory before importing a file to R, using


If possible change the path of your working directory. such as


Note you may have to create the directory (folder) and the path discussed above.

File Path

Reading Text (*.txt) Files

Reading Text (*.txt) files in R is easy and simple enough. If you have data in a *.txt file or a tab-delimited text file, you can easily import it with read.table( ) function. Suppose we have a data file named "Hald.txt" stored at path "D:\STAT\STA-654\Hald.txt". The following code line can be used for reading text (*.txt) files in R:

datafile <- read.table ("D:/stat/sta-654/Hald.txt", header = TRUE)

If you have data stored on some web address, you can also import it as

datafile <- read.table ("", header = TRUE)

Note that the first argument of read.table() provide the name and extension of the file that you want to import in R. the header argument specifies whether or not you have specified column names in your data file. The Hald.txt file will be imported as data.frame an object.

Reading Text (*.txt) Files

Leave a Reply

Scroll to top
x  Powerful Protection for WordPress, from Shield Security
This Site Is Protected By
Shield Security