How to read and write TXT files in R or import data from and export data to TXT files in R, using read.delim(), read.delim2(), and write.table().

The functions are from the "utils" package, hence, you do not need to do any installation.

Packages and Functions for Reading and Writing TXT Files in R
Activity Package Function
Read TXT utils read.delim() or read.delim2()
Write TXT utils write.table()
  • See the differences between read.delim() and read.delim2() below.

1 Read or Import Data from TXT Files in R

Download testdata.txt file.

The .txt file format is a text document containing plain text and uses tabs to separate the fields.

To read or import TXT or .txt files in R, after setting the working directory to the folder containing the file, use the line of code below:

If your data does not have header, set the header = FALSE.

read.delim(file = "testdata.txt", sep = "\t", header = TRUE)

Without setting the working directory, you can use the full file path of where the file is located to read the TXT or .txt file:

read.delim("C:/Users/Public/Statscodes/Rdata/read-files/testdata.txt", sep = "\t", header = TRUE)
TXT File Read in R

TXT File Read in R

Note that specifying the value for the "sep" argument as "slash t" allows us to indicate that the field separator is a tab. This is also the default value and can be changed to other values as needed such as "," for CSV data.

If your data uses a comma as decimal point, then use the read.delim2() function instead of read.delim() which is for cases where the data uses a period as decimal point.

2 Write or Export Data to TXT Files in R

The dataframe named dtfrm will be used:

dtfrm = data.frame(Group = c("A", "B", "B", "C", "D"), 
                   ID = c("A02", "B12", "B15", "C04", "D07"), 
                   Score = c(9, 8, 8, 10, 7), 
                   Position = c(2, 3, 3, 1, 5))
dtfrm
  Group  ID Score Position
1     A A02     9        2
2     B B12     8        3
3     B B15     8        3
4     C C04    10        1
5     D D07     7        5

To write or export data to TXT or .txt files in R to the working directory, use the line of code below:

write.table(dtfrm, file = "outdata.txt", sep = "\t")

Or specify a full file path of where you want to save the file:

write.table(dtfrm, file = "C:/Users/Public/Statscodes/Rdata/write-files/outdata.txt")

The output should look like this in Notepad:

TXT Output Written in R

TXT Output Written in R

To remove the row numbers on the first column, set row.names = FALSE as shown below.

write.table(dtfrm, file = "outdata2.txt", row.names = FALSE)

Or:

write.table(dtfrm, file = "C:/Users/Public/Statscodes/Rdata/write-files/outdata2.txt", row.names = FALSE)

The output should now look like this in Notepad:

TXT Output Without Row Numbers Written in R

TXT Output Without Row Numbers Written in R

Copyright © 2020 - 2024. All Rights Reserved by Stats Codes