[R]TSV形式でテキストファイルに高速で書き込む
readrパッケージのwrite_tsv関数を使う。以下は500万行からなるデータフレームをwrite.tableとwrite_tsv関数でそれぞれTSV形式のテキストファイルに3回ずつ出力し、それに要した時間を計測した例。write_tsv関数のほうが10倍以上速いことがわかる。
> library(readr)
> n <- 5 * 10 ^ 6
> no <- 1:n
> s <- c("大橋彩香", "石見舞菜香", "優木かな", "和多田美咲")
> name <- sample(s, n, replace = TRUE)
> shoe_size <- round(rnorm(n, 23.5, 1), 1)
> dtf <- data.frame(no, name, shoe_size)
> head(dtf, 6)
no name shoe_size
1 1 石見舞菜香 24.3
2 2 石見舞菜香 23.2
3 3 和多田美咲 23.6
4 4 大橋彩香 24.8
5 5 石見舞菜香 25.1
6 6 優木かな 24.7
> system.time(
+ write.table(dtf, "temp.tsv", sep = "\t", quote = FALSE, row.names = FALSE)
+ )
ユーザ システム 経過
9.86 0.06 12.78
> system.time(
+ write.table(dtf, "temp.tsv", sep = "\t", quote = FALSE, row.names = FALSE)
+ )
ユーザ システム 経過
9.43 0.14 12.94
> system.time(
+ write.table(dtf, "temp.tsv", sep = "\t", quote = FALSE, row.names = FALSE)
+ )
ユーザ システム 経過
9.55 0.09 13.06
> system.time(write_tsv(dtf, "temp.tsv", eol = "\r\n", progress = FALSE))
ユーザ システム 経過
0.60 0.05 0.16
> system.time(write_tsv(dtf, "temp.tsv", eol = "\r\n", progress = FALSE))
ユーザ システム 経過
0.62 0.10 0.16
> system.time(write_tsv(dtf, "temp.tsv", eol = "\r\n", progress = FALSE))
ユーザ システム 経過
0.92 0.07 0.84
« [R]正規表現を使用してファイル名を表す文字列から拡張子を抜き出す | トップページ | [R]leafletを使用して表示場所とズームレベルを指定して地理院地図を表示する »
「R(tidyverse)」カテゴリの記事
- [R]2つの列による重複を調べてその重複の数を表示する(2025.12.24)
- [R]tibbleから指定した一列を取り出してベクトルにする(2025.10.19)
- [R]tibbleを指定した列だけのtibbleに変換する(2025.10.14)
- [R]tibbleを指定した行だけのtibbleに変換する(2025.10.13)
- [R]tibbleの列名を得る(2025.07.17)
« [R]正規表現を使用してファイル名を表す文字列から拡張子を抜き出す | トップページ | [R]leafletを使用して表示場所とズームレベルを指定して地理院地図を表示する »

コメント