Reading Text (*.txt) Files

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

  1. Usually, data from spreadsheets reserved the first row as header (name of variables), while the first column was used to identify the sampling unit (observation number).
  2. Avoid names, and 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 abbreviated names.
  5. Try to avoid using names of variables that contain symbols such as ?, $, %, ^, *, (, ), -, #, <, >, /, |, ,\, [, ], {, and }.
  6. Delete comments you have made in your Excel file.
  7. Make sure missing values in your dataset are indicated with NA.

Preparing your 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

getwd()

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

setwd("D:\\Stat\\STA-654")

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

Reading Text (*.txt) Files

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 the read.table( ) function. Suppose we have a data file named "Hald.txt" stored at the 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 ("http://itfeature.com/wp-content/uploads/2020/03/Hald.txt", 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.

Computer MCQs Online Test

MCQs in Statistics

Leave a Reply