R read.table() Function - Reading Table Files
The R read.table() function is a lower-level general version of read.csv(), used to read delimited text files.
read.table() can handle files in various delimiter formats, such as TSV (tab-separated), fixed-width, etc.
The syntax of the read.table() function is as follows:
read.table(file, header = FALSE, sep = "", dec = ".",
comment.char = "#", na.strings = "NA")
Parameter description:
fileFile path.
headerWhether the first row is used as column names.
sepSeparator; an empty string means whitespace separation.
comment.charComment character; lines starting with this character are ignored.
na.stringsStrings 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 original 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("\n"Read back the data:")
print(data)
write.table(mtcars[1:5, 1:3], "temp_mtcars.tsv",
sep = "\t", row.names = FALSE)
# View the original 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("\n"Read back the data:")
print(data)
Executing the above code produces the following output:
[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 360Other Extensions
R Language Examples