R read.table() 関数 - テーブルファイルを読み込む
R read.table() 関数は read.csv() の低レベル汎用バージョンであり、区切り文字テキストファイルを読み込むために使用されます。
read.table() は、TSV(タブ区切り)、固定幅などのさまざまな区切り形式のファイルを処理できます。
read.table() 関数の構文は次のとおりです:
read.table(file, header = FALSE, sep = "", dec = ".",
comment.char = "#", na.strings = "NA")
パラメータの説明:
fileファイルパス。
header先頭行を列名として使用するかどうか。
sep区切り文字。空文字列は空白区切りを意味します。
comment.charコメント文字。この文字で始まる行は無視されます。
na.stringsNA 値として扱う文字列。
例
# タブ区切りファイルを書き込む
write.table(mtcars[1:5, 1:3], "temp_mtcars.tsv",
sep = "\t", row.names = FALSE)
# 元の内容を表示する
print("TSV ファイル内容:")
cat(readLines("temp_mtcars.tsv"), sep = "\n")
# タブ区切りファイルを読み込む
data <- read.table("temp_mtcars.tsv", header = TRUE, sep = "\t")
print("\n"読み戻したデータ:")
print(data)
write.table(mtcars[1:5, 1:3], "temp_mtcars.tsv",
sep = "\t", row.names = FALSE)
# 元の内容を表示する
print("TSV ファイル内容:")
cat(readLines("temp_mtcars.tsv"), sep = "\n")
# タブ区切りファイルを読み込む
data <- read.table("temp_mtcars.tsv", header = TRUE, sep = "\t")
print("\n"読み戻したデータ:")
print(data)
上記のコードを実行すると、出力結果は次のとおりです:
[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 言語の例