Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

R read.table() Function - Reading Table Files

R read.table() Function - Reading Table Files

R Language Examples R Language Examples

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:

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

print

(

"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"

)

print

(

"\nData read back:"

)

print

(

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 R Language Examples