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.
Activity | Package | Function |
Read TXT | utils | read.delim() or read.delim2() |
Write TXT | utils | write.table() |
read.delim()
and
read.delim2()
below.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
.
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:
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.
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:
Or specify a full file path of where you want to save the file:
The output should look like this in Notepad:
To remove the row numbers on the first column, set
row.names = FALSE
as shown below.
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:
The feedback form is a Google form but it does not collect any personal information.
Please click on the link below to go to the Google form.
Thank You!
Go to Feedback Form
Copyright © 2020 - 2024. All Rights Reserved by Stats Codes