How to Import a Text File into R

To import a text file into R:

read.csv("Path where the TXT file is stored\\File Name.txt")

Steps to Import a Text file into R

Step 1: Prepare the text file

To start, prepare a simple text file (called ‘Products‘) with the following data:

product,price
computer,800
monitor,450
keyboard,100
printer,150
tablet,300

Step 2: Capture the path of the file

Next, capture the full path where the file is stored on your computer.

For demonstration purposes, assume that the file is stored under the following path:

C:\\Users\\Ron\\Desktop\\Test\\Products.txt

Where:

  • The blue portion represents the file name to be imported. In our example, the file name is ‘Products
  • The green portion represents the file type, which is .txt

Also note that a double backslash (‘\\’) was used within the path name to avoid any errors in the path.

Step 3: Import the text file into R

Finally, use the following syntax (adjusted to your path) to import the text file into R:

read.csv("C:\\Users\\Ron\\Desktop\\Test\\Products.txt")

Here are the results that you’ll get:

   product price
1 computer   800
2  monitor   450
3 keyboard   100
4  printer   150
5   tablet   300

Alternatively, check the following guide for the steps to export a DataFrame to a text file in R.

Leave a Comment