Handling TXT files

Let's get our hands dirty by taking input from .txt files

Input Data from a File

R is one of the most popular languages for data manipulation and analysis. We can perform various statistical analysis with this language. However, the size of the data that we are talking about here is in Gigabytes or Terabytes. Such a large quantity of data cannot be entered by the user interactively from the keyboard. Therefore, data is fed into the system/program using external files.

Here, we will be learning how to take input from .txt files. Now, suppose we have this data stored in a file.

The format of the .txt file is:

Alex, California, 2025550167, F
Brian, NewYork, 2025354137, M
Charles, Boston, 2025339164, M

Steps to Take Input from File

  1. We need to specify the file name and its path in the local filesystem. If the text file is in the same directory as the R program, just the file name is enough. Open that file using this syntax:
fileData <- file(path, open = "r")

# path is the location of the file plus its name
# open = "r" specifies that we want to open the file in read-mode
  1. In the next step, we fetch all the data from the file. In this case, we fetch data from fileData. For this purpose, we use the function readLines(). The syntax is:
lines <- readLines(fileData)
  1. Now that all the lines of the files are stored in the variable lines, we can do any calculation or task on this data.

Let’s look at the complete code for inputting data from a .txt file and displaying its contents on the screen.

Create a free account to access the full course.

By signing up, you agree to Educative's Terms of Service and Privacy Policy