R read.table() Function - Reading Table Files
The R read.table() function is the lower-level general version of read.csv(), used to read delimited text files.
read.table() can handle files with various delimiters, such as TSV (tab-separated), fixed-width, and more.
The syntax of the read.table() function is as follows:
read.table(file, header = FALSE, sep = "", dec = ".",
comment.char = "#", na.strings = "NA")
Parameter Description:
-
file File path.
-
header Whether the first row is used as column names.
-
sep The separator; an empty string means whitespace separation.
-
comment.char The comment character; lines starting with it are ignored.
-
na.strings Strings to be treated as NA values.
Example
Write a tab-separated file
write.table
(
mtcars
[
1
:
5
,
1
:
3
]
,
"temp_mtcars.tsv"
,
sep
=
"\t"
,
row.names
=
FALSE
)
View the raw content
(
"TSV file content:"
)
cat
(
readLines
(
"temp_mtcars.tsv"
)
, sep
=
"\n"
)
Read the tab-separated file
data
<-
read.table
(
"temp_mtcars.tsv"
, header
=
TRUE, sep
=
"\t"
)
(
"\nData read back:"
)
(
data
)
The output of the code above is:
[1] "TSV 文件内容:"
"mpg" "cyl" "disp"
"21" "6" "160"
"21" "6" "160"
"22.8" "4" "108"
"21.4" "6" "258"
"18.7" "8" "360"
[1] "读回的数据:"
mpg cyl disp
1 21.0 6 160
2 21.0 6 160
3 22.8 4 108
4 21.4 6 258
5 18.7 8 360
R Language Examples