From 872dc8bab5dc386837ec87a47740c88c0518f341 Mon Sep 17 00:00:00 2001 From: venom1204 Date: Sun, 27 Jul 2025 08:23:04 +0000 Subject: [PATCH 01/15] added fwrite and fread vignette --- vignettes/datatable-fread-and-fwrite.Rmd | 331 +++++++++++++++++++++++ 1 file changed, 331 insertions(+) create mode 100644 vignettes/datatable-fread-and-fwrite.Rmd diff --git a/vignettes/datatable-fread-and-fwrite.Rmd b/vignettes/datatable-fread-and-fwrite.Rmd new file mode 100644 index 0000000000..764c340dbe --- /dev/null +++ b/vignettes/datatable-fread-and-fwrite.Rmd @@ -0,0 +1,331 @@ +--- +title: "fread() and fwrite()" +date: "`r Sys.Date()`" +output: rmarkdown::html_vignette # <--- Changed +vignette: > + %\VignetteIndexEntry{fread() and fwrite()} + %\VignetteEngine{knitr::rmarkdown} # <--- Changed + %\VignetteEncoding{UTF-8} # <--- Ensure this is present +--- + +```{r echo=FALSE, file='_translation_links.R'} +``` +`r .write.translation.links("Translations of this document are available in: %s")` + +```{r, echo = FALSE, message = FALSE} +require(data.table) +knitr::opts_chunk$set( + comment = "#", + error = FALSE, + tidy = FALSE, + cache = FALSE, + collapse = TRUE) +.old.th = setDTthreads(1) +``` + +The `fread()` and `fwrite()` functions in the `data.table` R package are not only optimized for speed on large files, but also offer powerful and convenient features for working with small datasets. This vignette highlights their usability, flexibility, and performance for efficient data import and export. + +*** + +## 1. **fread()** + +### **1.1 Using command line tools directly** +The `fread()` function from `data.table` can read data piped from shell commands, letting you filter or preprocess data before it even enters R. + +```{r} +# Create a sample file with some unwanted lines +writeLines( +'HEADER: Some metadata +HEADER: More metadata +1 2.0 3.0 +2 4.5 6.7 +HEADER: Yet more +3 8.9 0.1 +4 1.2 3.4', +"example_data.txt") + +library(data.table) +fread("grep -v HEADER example_data.txt") +``` + +The `-v` option makes `grep` return all lines except those containing the string 'HEADER'. Given the number of high quality engineers that have looked at the command tool grep over the years, it is most likely that it is as fast as you can get, as well as being correct, convenient, well documented online, easy to learn and search for solutions for specific tasks. If you need to perform more complex string filtering (e.g., matching strings at the beginning or end of lines), the `grep` syntax is very powerful. Learning its syntax is a transferable skill for other languages and environments. + +Look at this [example](https://stackoverflow.com/questions/36256706/fread-together-with-grepl/36270543#36270543) for more detail. + +On Windows we recommend [Cygwin](https://www.cygwin.com/) (run one .exe to install) which includes the command line tools such as grep. In March 2016, Microsoft [announced](https://www.hanselman.com/blog/developers-can-run-bash-shell-and-usermode-ubuntu-linux-binaries-on-windows-10) they will include these tools in Windows 10 natively. On Linux and macOS, these tools have always been included in the operating system. You can find many examples and tutorials about command line tools online. We recommend [Data Science at the Command Line](https://www.oreilly.com/library/view/data-science-at/9781491947845/). + +#### 1.1.1 **Reading directly from a text string** + +`fread()` can read data directly from a character string in R using the text argument. This is particularly handy for creating reproducible examples, testing code snippets, or working with data generated programmatically within your R session. Each line in the string should be separated by a newline character `( +)`. + +```{r} +my_data_string <- "colA,colB,colC\n1,apple,TRUE\n2,banana,FALSE\n3,orange,TRUE" +dt_from_text <- fread(text = my_data_string) +print(dt_from_text) +``` + +#### 1.1.2 **Reading from R connections and URLs** + +`fread()` is highly versatile and can accept R connection objects as input to its file (or input) argument. This allows you to read from various sources, including: + +- Web URLs: Directly download and read data from the internet. + +- Compressed files: Using connections like gzfile(), bzfile(), xzfile(). + +- Other connection types: Any R connection that supports text reading. + +#### 1.1.3 **Automatic decompression of compressed files** + +In many cases, `fread()` can automatically detect and decompress files with common compression extensions directly, without needing an explicit connection object like gzfile() or using shell commands. This works by checking the file extension. +Supported extensions typically include: +`.gz` (gzip) +`.bz2` (bzip2) +`.xz` (xz) +`.zip` (ZIP archives - `fread` will attempt to read the first file within the `.zip` archive if no specific file inside the archive is specified using the file#entry syntax, or if the `.zip` contains only one file. For more control over which file to read from a multi-file zip, see `?fread` examples for file#entry or use unzip first). +This functionality may rely on the `R.utils` package or system tools being available for some formats. + +```{r} +# 1. Create a sample data.table and write it to a gzipped CSV +set.seed(123) +original_dt <- data.table(A = 1:5, B = runif(5)) +fwrite(original_dt, "my_data_auto.csv.gz") # fwrite can also write directly to compressed files + +# 2. fread automatically decompresses and reads it +dt_auto_decompressed <- fread("my_data_auto.csv.gz") +print(dt_auto_decompressed) + +# Clean up +file.remove("my_data_auto.csv.gz") +``` + +### 1.2 **Automatic separator and skip detection** + +`fread` automates delimiter and header detection, eliminating the need for manual specification in most cases. You simply provide the filename—`fread` intelligently detects the structure: + +**Separator Detection** + +`fread` tests common separators (`,`,`\t`, `|`, space, `:`, `;`) and selects the one that results in the most consistent number of fields across sampled rows. For non-standard delimiters, you can override this using the `sep=` parameter. + +**Header Detection** + +After applying any `skip` or `nrows` settings (if specified), the first row with a consistent number of fields is examined: + +If all fields in this line are interpretable as character and the values do not strongly resemble a data row (e.g., a row of purely numeric-looking strings might still be considered data), it is typically used as the header (column names). + +Otherwise (e.g., if the line contains detected numeric types, or character strings that strongly resemble numbers and could be data), it is treated as a data row, and default column names (`V1`, `V2`, …) are assigned. + +You can explicitly tell fread whether a header exists using `header = TRUE` or `header = FALSE`. + +**Skip Detection** + +By default (`skip="auto"`), `fread` will automatically skip blank lines and comment lines (e.g., starting with `#`) before the data header. To manually skip a specific number of lines, use `skip=n`. + +### 1.3 **High-Quality Automatic Column Type Detection** + +Many real-world datasets contain columns that are initially blank, zero-filled, or appear numeric but later contain characters. To handle such inconsistencies, `fread()` in `data.table` employs a robust column type detection strategy. + +Since v1.10.5, `fread()` samples 10,000 rows by reading 100 contiguous rows from 100 equally spaced points across the file, including the start, middle, and end. This wide sampling helps detect type changes that occur later in the data (e.g., `001` to `0A0` or blanks becoming populated). + +**Efficient File Access with mmap** + +To implement this sampling efficiently, `fread()` uses the operating system's memory-mapped file access (`mmap`), allowing it to jump to arbitrary positions in the file without sequential scanning. This lazy, on-demand strategy makes sampling nearly instantaneous, even for very large files. + +If a jump lands within a quoted field that includes newlines, `fread()` tests subsequent lines until it finds 5 consecutive rows with the expected number of fields, ensuring correct parsing even in complex files. + +**Accurate and Optimized Type Detection** + +The type for each column is inferred based on the lowest required type from the following ordered list: + +`logical` < `integer` < `integer64` < `double` < `character` + +This ensures: + +- Single up-front allocation of memory using the correct type +- Avoidance of rereading the file or manually setting colClasses +- Improved speed and memory efficiency + +**Out-of-Sample Type Exceptions** + +If a type change occurs outside the sampled rows, `fread()` automatically detects it and rereads only the affected columns from the beginning. This ensures correct type assignment without requiring user intervention. For example, a column sampled as integer might later contain `00A` — triggering an automatic reread as character. + +All detection logic and any rereads are detailed when `verbose=TRUE` is enabled. + +### 1.4 **Early Error Detection at End-of-File** + +Because the large sample explicitly includes the very end of the file, critical issues—such as an inconsistent number of columns, a malformed footer, or an opening quote without a matching closing quote—can be detected and reported almost instantly. This early error detection avoids the unnecessary overhead of processing the entire file or allocating excessive memory, only to encounter a failure at the final step. It ensures faster feedback and more efficient resource usage, especially when working with large datasets. + +### 1.5 **Reading SQL Insert Scripts** + +`fread()` doesn't directly support SQL `INSERT` scripts, but they can be processed via command-line tools. For example, given `insert_script.sql`: + +```{SQL} +INSERT INTO tbl VALUES (1, 'asd', 923123123, 'zx'); +INSERT INTO tbl VALUES (1, NULL, 923123123, 'zxz'); +INSERT INTO tbl VALUES (3, 'asd3', 923123123, NULL); +``` + +Use this command in R [link](https://stackoverflow.com/questions/32026398/transform-sql-insert-script-into-csv-format): + +```{r} +# 1. Create the SQL file programmatically +writeLines( +c( +"INSERT INTO tbl VALUES (1, 'asd', 923123123, 'zx');", +"INSERT INTO tbl VALUES (1, NULL, 923123123, 'zxz');", +"INSERT INTO tbl VALUES (3, 'asd3', 923123123, NULL);" +), +"insert_script.sql" +) + +# 2. Process with awk and read into R +dt_sql <- fread(cmd = "awk -F' *[(),]+ *' -v OFS=, '{for (i=2; i<=NF-1; i++) printf \"%s%s\", ($i), (i Date: Sun, 27 Jul 2025 10:03:56 +0000 Subject: [PATCH 02/15] .. --- vignettes/datatable-fread-and-fwrite.Rmd | 16 ++++++++++++---- 1 file changed, 12 insertions(+), 4 deletions(-) diff --git a/vignettes/datatable-fread-and-fwrite.Rmd b/vignettes/datatable-fread-and-fwrite.Rmd index 764c340dbe..1c6732b89e 100644 --- a/vignettes/datatable-fread-and-fwrite.Rmd +++ b/vignettes/datatable-fread-and-fwrite.Rmd @@ -45,7 +45,12 @@ HEADER: Yet more "example_data.txt") library(data.table) -fread("grep -v HEADER example_data.txt") + +all_lines <- readLines("example_data.txt") +data_lines <- grep("HEADER", all_lines, value = TRUE, invert = TRUE) +fread(text = data_lines) + +file.remove("example_data.txt") ``` The `-v` option makes `grep` return all lines except those containing the string 'HEADER'. Given the number of high quality engineers that have looked at the command tool grep over the years, it is most likely that it is as fast as you can get, as well as being correct, convenient, well documented online, easy to learn and search for solutions for specific tasks. If you need to perform more complex string filtering (e.g., matching strings at the beginning or end of lines), the `grep` syntax is very powerful. Learning its syntax is a transferable skill for other languages and environments. @@ -177,11 +182,14 @@ c( ), "insert_script.sql" ) +sql_lines <- readLines("insert_script.sql") -# 2. Process with awk and read into R -dt_sql <- fread(cmd = "awk -F' *[(),]+ *' -v OFS=, '{for (i=2; i<=NF-1; i++) printf \"%s%s\", ($i), (i Date: Sun, 27 Jul 2025 10:51:28 +0000 Subject: [PATCH 03/15] <- by = --- vignettes/datatable-fread-and-fwrite.Rmd | 68 +++++++++--------------- 1 file changed, 26 insertions(+), 42 deletions(-) diff --git a/vignettes/datatable-fread-and-fwrite.Rmd b/vignettes/datatable-fread-and-fwrite.Rmd index 1c6732b89e..c5abdeb28f 100644 --- a/vignettes/datatable-fread-and-fwrite.Rmd +++ b/vignettes/datatable-fread-and-fwrite.Rmd @@ -1,5 +1,5 @@ --- -title: "fread() and fwrite()" +title: "Fast read and fast write" date: "`r Sys.Date()`" output: rmarkdown::html_vignette # <--- Changed vignette: > @@ -46,8 +46,8 @@ HEADER: Yet more library(data.table) -all_lines <- readLines("example_data.txt") -data_lines <- grep("HEADER", all_lines, value = TRUE, invert = TRUE) +all_lines = readLines("example_data.txt") +data_lines = grep("HEADER", all_lines, value = TRUE, invert = TRUE) fread(text = data_lines) file.remove("example_data.txt") @@ -65,44 +65,28 @@ On Windows we recommend [Cygwin](https://www.cygwin.com/) (run one .exe to insta )`. ```{r} -my_data_string <- "colA,colB,colC\n1,apple,TRUE\n2,banana,FALSE\n3,orange,TRUE" -dt_from_text <- fread(text = my_data_string) +my_data_string = "colA,colB,colC\n1,apple,TRUE\n2,banana,FALSE\n3,orange,TRUE" +dt_from_text = fread(text = my_data_string) print(dt_from_text) ``` -#### 1.1.2 **Reading from R connections and URLs** +#### 1.1.2 **Reading from URLs** -`fread()` is highly versatile and can accept R connection objects as input to its file (or input) argument. This allows you to read from various sources, including: +`fread()` can read data directly from web URLs by passing the URL as a character string to its `file` argument. This allows you to download and read data from the internet in one step. -- Web URLs: Directly download and read data from the internet. - -- Compressed files: Using connections like gzfile(), bzfile(), xzfile(). - -- Other connection types: Any R connection that supports text reading. + ```{r} + # dt = fread("https://people.sc.fsu.edu/~jburkardt/data/csv/airtravel.csv") + # print(dt) + ``` #### 1.1.3 **Automatic decompression of compressed files** -In many cases, `fread()` can automatically detect and decompress files with common compression extensions directly, without needing an explicit connection object like gzfile() or using shell commands. This works by checking the file extension. -Supported extensions typically include: -`.gz` (gzip) -`.bz2` (bzip2) -`.xz` (xz) -`.zip` (ZIP archives - `fread` will attempt to read the first file within the `.zip` archive if no specific file inside the archive is specified using the file#entry syntax, or if the `.zip` contains only one file. For more control over which file to read from a multi-file zip, see `?fread` examples for file#entry or use unzip first). -This functionality may rely on the `R.utils` package or system tools being available for some formats. - -```{r} -# 1. Create a sample data.table and write it to a gzipped CSV -set.seed(123) -original_dt <- data.table(A = 1:5, B = runif(5)) -fwrite(original_dt, "my_data_auto.csv.gz") # fwrite can also write directly to compressed files - -# 2. fread automatically decompresses and reads it -dt_auto_decompressed <- fread("my_data_auto.csv.gz") -print(dt_auto_decompressed) +In many cases, `fread()` can automatically detect and decompress files with common compression extensions directly, without needing an explicit connection object or shell commands. This works by checking the file extension. -# Clean up -file.remove("my_data_auto.csv.gz") -``` +**Supported extensions typically include:** +- `.gz` (gzip): Supported and works out of the box. +- `.xz` (xz): Supported and works out of the box. +- `.zip` (ZIP archives, single file): Supported—`fread()` will read the first file in the archive if only one file is present. ### 1.2 **Automatic separator and skip detection** @@ -182,11 +166,11 @@ c( ), "insert_script.sql" ) -sql_lines <- readLines("insert_script.sql") +sql_lines = readLines("insert_script.sql") -values_only <- gsub("INSERT INTO tbl VALUES \\((.*)\\);", "\\1", sql_lines) +values_only = gsub("INSERT INTO tbl VALUES \\((.*)\\);", "\\1", sql_lines) -dt_sql <- fread(text = values_only, na.strings = "NULL") +dt_sql = fread(text = values_only, na.strings = "NULL") print(dt_sql) file.remove("insert_script.sql") @@ -275,12 +259,12 @@ When data is written as strings (either inherently, like character columns, or b **Bypassed for Direct Numeric Output**: If specific columns are written as their underlying numeric types (e.g., via `dateTimeAs="epoch"` for POSIXct, or if a user pre-converts Date to integer), then quoting logic is naturally bypassed for those numeric fields, contributing to efficiency. ```{r} -dt_quoting_scenario <- data.table( +dt_quoting_scenario = data.table( text_field = c("Contains,a,comma", "Contains \"a quote\"", "Contains\na newline", "Clean_text"), epoch_time = as.numeric(as.POSIXct("2023-10-26 14:35:00", tz = "GMT") + 1:4), # Already numeric numeric_field = 1:4 ) -temp_quote_adv <- tempfile(fileext = ".csv") +temp_quote_adv = tempfile(fileext = ".csv") # Quoting applies to text_field, but not to epoch_time or numeric_field fwrite(dt_quoting_scenario, temp_quote_adv) @@ -296,11 +280,11 @@ Offers precise control for POSIXct/Date types: - `dateTimeAs="epoch"`: POSIXct as seconds since epoch (numeric). ```{r} -dt_timestamps <- data.table( +dt_timestamps = data.table( ts = as.POSIXct("2023-10-26 14:35:45.123456", tz = "GMT"), dt = as.Date("2023-11-15") ) -temp_dt_iso <- tempfile(fileext = ".csv") +temp_dt_iso = tempfile(fileext = ".csv") fwrite(dt_timestamps, temp_dt_iso, dateTimeAs = "ISO") cat(readLines(temp_dt_iso), sep = "\n") unlink(temp_dt_iso) @@ -314,8 +298,8 @@ unlink(temp_dt_iso) ```{r} if (requireNamespace("bit64", quietly = TRUE)) { - dt_i64 <- data.table(uid = bit64::as.integer64("1234567890123456789"), val = 100) - temp_i64_out <- tempfile(fileext = ".csv") + dt_i64 = data.table(uid = bit64::as.integer64("1234567890123456789"), val = 100) + temp_i64_out = tempfile(fileext = ".csv") fwrite(dt_i64, temp_i64_out) cat(readLines(temp_i64_out), sep = "\n") @@ -328,7 +312,7 @@ if (requireNamespace("bit64", quietly = TRUE)) { To control the order and subset of columns written to file, subset the data.table before calling `fwrite()`. The `col.names` argument in `fwrite()` is a logical (TRUE/FALSE) that controls whether the header row is written, not which columns are written. ```{r} -dt <- data.table(A = 1:3, B = 4:6, C = 7:9) +dt = data.table(A = 1:3, B = 4:6, C = 7:9) # Write only columns C and A, in that order fwrite(dt[, .(C, A)], "out.csv") From e468e20d26c3be609389a30b9bb11690950ee448 Mon Sep 17 00:00:00 2001 From: venom1204 Date: Sun, 27 Jul 2025 11:04:27 +0000 Subject: [PATCH 04/15] .. --- vignettes/datatable-fread-and-fwrite.Rmd | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/vignettes/datatable-fread-and-fwrite.Rmd b/vignettes/datatable-fread-and-fwrite.Rmd index c5abdeb28f..6d39d0cc23 100644 --- a/vignettes/datatable-fread-and-fwrite.Rmd +++ b/vignettes/datatable-fread-and-fwrite.Rmd @@ -57,7 +57,7 @@ The `-v` option makes `grep` return all lines except those containing the string Look at this [example](https://stackoverflow.com/questions/36256706/fread-together-with-grepl/36270543#36270543) for more detail. -On Windows we recommend [Cygwin](https://www.cygwin.com/) (run one .exe to install) which includes the command line tools such as grep. In March 2016, Microsoft [announced](https://www.hanselman.com/blog/developers-can-run-bash-shell-and-usermode-ubuntu-linux-binaries-on-windows-10) they will include these tools in Windows 10 natively. On Linux and macOS, these tools have always been included in the operating system. You can find many examples and tutorials about command line tools online. We recommend [Data Science at the Command Line](https://www.oreilly.com/library/view/data-science-at/9781491947845/). +On Windows we recommend [Cygwin](https://www.cygwin.com/) (run one .exe to install) which includes the command line tools such as grep. In March 2016, Microsoft [announced](https://www.hanselman.com/blog/developers-can-run-bash-shell-and-usermode-ubuntu-linux-binaries-on-windows-10) they will include these tools in Windows 10 natively. On Linux and macOS, these tools have always been included in the operating system. You can find many examples and tutorials about command line tools online. #### 1.1.1 **Reading directly from a text string** @@ -148,10 +148,11 @@ Because the large sample explicitly includes the very end of the file, critical `fread()` doesn't directly support SQL `INSERT` scripts, but they can be processed via command-line tools. For example, given `insert_script.sql`: -```{SQL} -INSERT INTO tbl VALUES (1, 'asd', 923123123, 'zx'); -INSERT INTO tbl VALUES (1, NULL, 923123123, 'zxz'); -INSERT INTO tbl VALUES (3, 'asd3', 923123123, NULL); +```{r, eval=FALSE} +# Example SQL insert statements: +# INSERT INTO tbl VALUES (1, 'asd', 923123123, 'zx'); +# INSERT INTO tbl VALUES (1, NULL, 923123123, 'zxz'); +# INSERT INTO tbl VALUES (3, 'asd3', 923123123, NULL); ``` Use this command in R [link](https://stackoverflow.com/questions/32026398/transform-sql-insert-script-into-csv-format): From 8fb7ed6f9b58e8ef6a943ee70bdc8b88e025ed38 Mon Sep 17 00:00:00 2001 From: venom1204 Date: Sun, 27 Jul 2025 11:41:10 +0000 Subject: [PATCH 05/15] titel change --- vignettes/datatable-fread-and-fwrite.Rmd | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/vignettes/datatable-fread-and-fwrite.Rmd b/vignettes/datatable-fread-and-fwrite.Rmd index 6d39d0cc23..3e80fb6e2d 100644 --- a/vignettes/datatable-fread-and-fwrite.Rmd +++ b/vignettes/datatable-fread-and-fwrite.Rmd @@ -1,9 +1,9 @@ --- -title: "Fast read and fast write" +title: "Fast Read and Fast Write" date: "`r Sys.Date()`" output: rmarkdown::html_vignette # <--- Changed vignette: > - %\VignetteIndexEntry{fread() and fwrite()} + %\VignetteIndexEntry{Fast Read and Fast Write} %\VignetteEngine{knitr::rmarkdown} # <--- Changed %\VignetteEncoding{UTF-8} # <--- Ensure this is present --- From 70a8992f881f52f4ebaee6f076c9aace606ff8a5 Mon Sep 17 00:00:00 2001 From: venom1204 Date: Sun, 27 Jul 2025 18:53:43 +0000 Subject: [PATCH 06/15] updated --- vignettes/datatable-fread-and-fwrite.Rmd | 69 +++++++++++------------- 1 file changed, 32 insertions(+), 37 deletions(-) diff --git a/vignettes/datatable-fread-and-fwrite.Rmd b/vignettes/datatable-fread-and-fwrite.Rmd index 3e80fb6e2d..6237c1adb7 100644 --- a/vignettes/datatable-fread-and-fwrite.Rmd +++ b/vignettes/datatable-fread-and-fwrite.Rmd @@ -1,11 +1,12 @@ --- title: "Fast Read and Fast Write" date: "`r Sys.Date()`" -output: rmarkdown::html_vignette # <--- Changed +output: + markdown::html_format vignette: > - %\VignetteIndexEntry{Fast Read and Fast Write} - %\VignetteEngine{knitr::rmarkdown} # <--- Changed - %\VignetteEncoding{UTF-8} # <--- Ensure this is present + %\VignetteIndexEntry{Importing data.table} + %\VignetteEngine{knitr::knitr} + \usepackage[utf8]{inputenc} --- ```{r echo=FALSE, file='_translation_links.R'} @@ -27,7 +28,7 @@ The `fread()` and `fwrite()` functions in the `data.table` R package are not onl *** -## 1. **fread()** +## 1. fread() ### **1.1 Using command line tools directly** The `fread()` function from `data.table` can read data piped from shell commands, letting you filter or preprocess data before it even enters R. @@ -45,21 +46,16 @@ HEADER: Yet more "example_data.txt") library(data.table) - -all_lines = readLines("example_data.txt") -data_lines = grep("HEADER", all_lines, value = TRUE, invert = TRUE) -fread(text = data_lines) - -file.remove("example_data.txt") +fread("grep -v HEADER example_data.txt") ``` The `-v` option makes `grep` return all lines except those containing the string 'HEADER'. Given the number of high quality engineers that have looked at the command tool grep over the years, it is most likely that it is as fast as you can get, as well as being correct, convenient, well documented online, easy to learn and search for solutions for specific tasks. If you need to perform more complex string filtering (e.g., matching strings at the beginning or end of lines), the `grep` syntax is very powerful. Learning its syntax is a transferable skill for other languages and environments. - + Look at this [example](https://stackoverflow.com/questions/36256706/fread-together-with-grepl/36270543#36270543) for more detail. -On Windows we recommend [Cygwin](https://www.cygwin.com/) (run one .exe to install) which includes the command line tools such as grep. In March 2016, Microsoft [announced](https://www.hanselman.com/blog/developers-can-run-bash-shell-and-usermode-ubuntu-linux-binaries-on-windows-10) they will include these tools in Windows 10 natively. On Linux and macOS, these tools have always been included in the operating system. You can find many examples and tutorials about command line tools online. +On Windows we recommend [Cygwin](https://www.cygwin.com/) (run one .exe to install) which includes the command line tools such as grep. In March 2016, Microsoft [announced](https://www.hanselman.com/blog/developers-can-run-bash-shell-and-usermode-ubuntu-linux-binaries-on-windows-10) they will include these tools in Windows 10 natively. On Linux and macOS, these tools have always been included in the operating system. You can find many examples and tutorials about command line tools online. We recommend [Data Science at the Command Line](https://www.oreilly.com/library/view/data-science-at/9781491947845/). -#### 1.1.1 **Reading directly from a text string** +#### 1.1.1 Reading directly from a text string `fread()` can read data directly from a character string in R using the text argument. This is particularly handy for creating reproducible examples, testing code snippets, or working with data generated programmatically within your R session. Each line in the string should be separated by a newline character `( )`. @@ -70,7 +66,7 @@ dt_from_text = fread(text = my_data_string) print(dt_from_text) ``` -#### 1.1.2 **Reading from URLs** +#### 1.1.2 Reading from URLs `fread()` can read data directly from web URLs by passing the URL as a character string to its `file` argument. This allows you to download and read data from the internet in one step. @@ -79,7 +75,7 @@ print(dt_from_text) # print(dt) ``` -#### 1.1.3 **Automatic decompression of compressed files** +#### 1.1.3 Automatic decompression of compressed files In many cases, `fread()` can automatically detect and decompress files with common compression extensions directly, without needing an explicit connection object or shell commands. This works by checking the file extension. @@ -88,7 +84,7 @@ In many cases, `fread()` can automatically detect and decompress files with comm - `.xz` (xz): Supported and works out of the box. - `.zip` (ZIP archives, single file): Supported—`fread()` will read the first file in the archive if only one file is present. -### 1.2 **Automatic separator and skip detection** +### 1.2 Automatic separator and skip detection `fread` automates delimiter and header detection, eliminating the need for manual specification in most cases. You simply provide the filename—`fread` intelligently detects the structure: @@ -110,11 +106,11 @@ You can explicitly tell fread whether a header exists using `header = TRUE` or ` By default (`skip="auto"`), `fread` will automatically skip blank lines and comment lines (e.g., starting with `#`) before the data header. To manually skip a specific number of lines, use `skip=n`. -### 1.3 **High-Quality Automatic Column Type Detection** +### 1.3 High-Quality Automatic Column Type Detection Many real-world datasets contain columns that are initially blank, zero-filled, or appear numeric but later contain characters. To handle such inconsistencies, `fread()` in `data.table` employs a robust column type detection strategy. -Since v1.10.5, `fread()` samples 10,000 rows by reading 100 contiguous rows from 100 equally spaced points across the file, including the start, middle, and end. This wide sampling helps detect type changes that occur later in the data (e.g., `001` to `0A0` or blanks becoming populated). +Since v1.10.5, `fread()` samples rows by reading blocks of contiguous rows from multiple equally spaced points across the file, including the start, middle, and end. The total number of rows sampled is chosen dynamically based on the file size and structure, and is typically around 10,000, but can be smaller or slightly larger. This wide sampling helps detect type changes that occur later in the data (e.g., `001` to `0A0` or blanks becoming populated). **Efficient File Access with mmap** @@ -140,19 +136,18 @@ If a type change occurs outside the sampled rows, `fread()` automatically detect All detection logic and any rereads are detailed when `verbose=TRUE` is enabled. -### 1.4 **Early Error Detection at End-of-File** +### 1.4 Early Error Detection at End-of-File Because the large sample explicitly includes the very end of the file, critical issues—such as an inconsistent number of columns, a malformed footer, or an opening quote without a matching closing quote—can be detected and reported almost instantly. This early error detection avoids the unnecessary overhead of processing the entire file or allocating excessive memory, only to encounter a failure at the final step. It ensures faster feedback and more efficient resource usage, especially when working with large datasets. -### 1.5 **Reading SQL Insert Scripts** +### 1.5 Reading SQL Insert Scripts `fread()` doesn't directly support SQL `INSERT` scripts, but they can be processed via command-line tools. For example, given `insert_script.sql`: -```{r, eval=FALSE} -# Example SQL insert statements: -# INSERT INTO tbl VALUES (1, 'asd', 923123123, 'zx'); -# INSERT INTO tbl VALUES (1, NULL, 923123123, 'zxz'); -# INSERT INTO tbl VALUES (3, 'asd3', 923123123, NULL); +``` +INSERT INTO tbl VALUES (1, 'asd', 923123123, 'zx'); +INSERT INTO tbl VALUES (1, NULL, 923123123, 'zxz'); +INSERT INTO tbl VALUES (3, 'asd3', 923123123, NULL); ``` Use this command in R [link](https://stackoverflow.com/questions/32026398/transform-sql-insert-script-into-csv-format): @@ -177,15 +172,15 @@ print(dt_sql) file.remove("insert_script.sql") ``` -- The `awk` command transforms each INSERT line into a comma-separated list of its values. +- The `gsub()` function in R transforms each INSERT line into a comma-separated list of its values. - `na.strings = "NULL"` in fread is crucial: it tells fread to interpret the literal string `"NULL"` (output by awk for SQL NULLs) as R's NA value. -- Quoted strings (e.g., 'asd') are preserved by awk and read as character by `fread`. +- Quoted strings (e.g., 'asd') are preserved and read as character by `fread`. -### 1.6 **`integer64` Support** +### 1.6 `integer64` Support -By default, `fread` detects integers larger than 2³¹ and reads them as `bit64::integer64` to preserve full precision. This behavior can be overridden in three ways: +By default, `fread` detects integers larger than 231 and reads them as `bit64::integer64` to preserve full precision. This behavior can be overridden in three ways: - Per-column: Use the `colClasses` argument to specify the type for individual columns. @@ -209,7 +204,7 @@ options(datatable.integer64 = "double") # Example: set globally to "double" getOption("datatable.integer64") ``` -### 1.7 **Drop or Select Columns by Name or Position** +### 1.7 Drop or Select Columns by Name or Position To save memory and improve performance, use `fread()`'s `select` or `drop` arguments to read only the columns you need. @@ -224,11 +219,11 @@ Key points: For details, see the manual page by running `?fread` in R. -### 1.8 **Skip to a Sub-Table’s Header Row Using a Column Name Substring** +### 1.8 Skip to a Sub-Table’s Header Row Using a Column Name Substring Use `skip="string"` in `fread` to search for a line containing a substring (typically from the column names, e.g., `skip="Date"`). Reading begins at the first matching line. This is useful for skipping metadata or selecting sub-tables in multi-table files. This feature is inspired by the `read.xls` function in the gdata package. -### 1.9 **Automatic Quote Escape Detection (Including No-Escape)** +### 1.9 Automatic Quote Escape Detection (Including No-Escape) `fread` automatically detects how quotes are escaped—including doubled ("") or backslash-escaped (\") quotes—without requiring user input. This is determined using a large sample of the data (see point 3), and validated against the entire file. @@ -251,7 +246,7 @@ From v1.10.6, `fread` resolves ambiguities more reliably across the entire file `fwrite()` is the fast file writer companion to `fread()`. It’s designed for speed, sensible defaults, and ease of use, mirroring many of the conveniences found in fread`. -### 2.1 **Intelligent and Minimalist Quoting (quote="auto")** +### 2.1 Intelligent and Minimalist Quoting (quote="auto") When data is written as strings (either inherently, like character columns, or by choice, like `dateTimeAs="ISO"`), `quote="auto"` (default) intelligently quotes fields: @@ -272,7 +267,7 @@ fwrite(dt_quoting_scenario, temp_quote_adv) cat(readLines(temp_quote_adv), sep = "\n") ``` -### 2.2 **Fine-Grained Date/Time Serialization (dateTimeAs)** +### 2.2 Fine-Grained Date/Time Serialization (dateTimeAs) Offers precise control for POSIXct/Date types: @@ -291,7 +286,7 @@ cat(readLines(temp_dt_iso), sep = "\n") unlink(temp_dt_iso) ``` -### 2.3 **Handling of bit64::integer64** +### 2.3 Handling of bit64::integer64 **Full Precision for Large Integers**: `fwrite` writes `bit64::integer64` columns by converting them to strings with full precision. This prevents data loss or silent conversion to double that might occur with less specialized writers. This is crucial for IDs or measurements requiring more than R's standard `32-bit` integer range or `53-bit` double precision. @@ -308,7 +303,7 @@ if (requireNamespace("bit64", quietly = TRUE)) { } ``` -### 2.4 **Column Order and Subset Control** +### 2.4 Column Order and Subset Control To control the order and subset of columns written to file, subset the data.table before calling `fwrite()`. The `col.names` argument in `fwrite()` is a logical (TRUE/FALSE) that controls whether the header row is written, not which columns are written. From 77f26c44fa7c772396c90436aa6d356e2c7a8568 Mon Sep 17 00:00:00 2001 From: venom1204 Date: Wed, 30 Jul 2025 06:09:34 +0000 Subject: [PATCH 07/15] added changes suggested by ben-schwen --- vignettes/datatable-fread-and-fwrite.Rmd | 14 ++++++++++---- 1 file changed, 10 insertions(+), 4 deletions(-) diff --git a/vignettes/datatable-fread-and-fwrite.Rmd b/vignettes/datatable-fread-and-fwrite.Rmd index 6237c1adb7..e38d36391a 100644 --- a/vignettes/datatable-fread-and-fwrite.Rmd +++ b/vignettes/datatable-fread-and-fwrite.Rmd @@ -49,16 +49,19 @@ library(data.table) fread("grep -v HEADER example_data.txt") ``` -The `-v` option makes `grep` return all lines except those containing the string 'HEADER'. Given the number of high quality engineers that have looked at the command tool grep over the years, it is most likely that it is as fast as you can get, as well as being correct, convenient, well documented online, easy to learn and search for solutions for specific tasks. If you need to perform more complex string filtering (e.g., matching strings at the beginning or end of lines), the `grep` syntax is very powerful. Learning its syntax is a transferable skill for other languages and environments. - +The `-v` option makes `grep` return all lines except those containing the string 'HEADER'. + +> "Given the number of high quality engineers that have looked at the command tool grep over the years, it is most likely that it is as fast as you can get, as well as being correct, convenient, well documented online, easy to learn and search for solutions for specific tasks. If you need to perform more complex string filtering (e.g., matching strings at the beginning or end of lines), the grep syntax is very powerful. Learning its syntax is a transferable skill for other languages and environments." +> +> — Matt Dowle + Look at this [example](https://stackoverflow.com/questions/36256706/fread-together-with-grepl/36270543#36270543) for more detail. On Windows we recommend [Cygwin](https://www.cygwin.com/) (run one .exe to install) which includes the command line tools such as grep. In March 2016, Microsoft [announced](https://www.hanselman.com/blog/developers-can-run-bash-shell-and-usermode-ubuntu-linux-binaries-on-windows-10) they will include these tools in Windows 10 natively. On Linux and macOS, these tools have always been included in the operating system. You can find many examples and tutorials about command line tools online. We recommend [Data Science at the Command Line](https://www.oreilly.com/library/view/data-science-at/9781491947845/). #### 1.1.1 Reading directly from a text string -`fread()` can read data directly from a character string in R using the text argument. This is particularly handy for creating reproducible examples, testing code snippets, or working with data generated programmatically within your R session. Each line in the string should be separated by a newline character `( -)`. +`fread()` can read data directly from a character string in R using the text argument. This is particularly handy for creating reproducible examples, testing code snippets, or working with data generated programmatically within your R session. Each line in the string should be separated by a newline character `\n`. ```{r} my_data_string = "colA,colB,colC\n1,apple,TRUE\n2,banana,FALSE\n3,orange,TRUE" @@ -83,6 +86,9 @@ In many cases, `fread()` can automatically detect and decompress files with comm - `.gz` (gzip): Supported and works out of the box. - `.xz` (xz): Supported and works out of the box. - `.zip` (ZIP archives, single file): Supported—`fread()` will read the first file in the archive if only one file is present. +- `.tar` (tar archives, single file): Supported—`fread()` will read the first file in the archive if only one file is present. + +> Note: If there are multiple files in the archive, `fread()` will fail with an error. ### 1.2 Automatic separator and skip detection From e3f13bf741f39a5c4becbba7731acf107861b339 Mon Sep 17 00:00:00 2001 From: venom1204 Date: Wed, 30 Jul 2025 10:39:47 +0000 Subject: [PATCH 08/15] updated --- vignettes/datatable-fread-and-fwrite.Rmd | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/vignettes/datatable-fread-and-fwrite.Rmd b/vignettes/datatable-fread-and-fwrite.Rmd index e38d36391a..37827ca978 100644 --- a/vignettes/datatable-fread-and-fwrite.Rmd +++ b/vignettes/datatable-fread-and-fwrite.Rmd @@ -138,7 +138,7 @@ This ensures: **Out-of-Sample Type Exceptions** -If a type change occurs outside the sampled rows, `fread()` automatically detects it and rereads only the affected columns from the beginning. This ensures correct type assignment without requiring user intervention. For example, a column sampled as integer might later contain `00A` — triggering an automatic reread as character. +If a type change occurs outside the sampled rows, `fread()` automatically detects it and rereads the file to ensure correct type assignment, without requiring user intervention. For example, a column sampled as integer might later contain `00A` — triggering an automatic reread as character. All detection logic and any rereads are detailed when `verbose=TRUE` is enabled. @@ -198,7 +198,7 @@ The integer64 argument (and corresponding option) accepts the following values: - `"integer64"` (default): Reads large integers as `bit64::integer64` with full precision. -- `"double"` or `"numeric"`: Reads large integers as double-precision numbers, potentially losing precision silently (similar to base R). +- `"double"` or `"numeric"`: Reads large integers as double-precision numbers, potentially losing precision silently (similar to `utils::read.csv` in base R). - `"character"`: Reads large integers as character strings. From 6375f719574f9ca8a5f72159f11456ef8f9af30d Mon Sep 17 00:00:00 2001 From: venom1204 Date: Thu, 31 Jul 2025 07:33:58 +0000 Subject: [PATCH 09/15] removed section 1.5 --- vignettes/datatable-fread-and-fwrite.Rmd | 46 +++--------------------- 1 file changed, 4 insertions(+), 42 deletions(-) diff --git a/vignettes/datatable-fread-and-fwrite.Rmd b/vignettes/datatable-fread-and-fwrite.Rmd index 37827ca978..81f681c44d 100644 --- a/vignettes/datatable-fread-and-fwrite.Rmd +++ b/vignettes/datatable-fread-and-fwrite.Rmd @@ -146,45 +146,7 @@ All detection logic and any rereads are detailed when `verbose=TRUE` is enabled. Because the large sample explicitly includes the very end of the file, critical issues—such as an inconsistent number of columns, a malformed footer, or an opening quote without a matching closing quote—can be detected and reported almost instantly. This early error detection avoids the unnecessary overhead of processing the entire file or allocating excessive memory, only to encounter a failure at the final step. It ensures faster feedback and more efficient resource usage, especially when working with large datasets. -### 1.5 Reading SQL Insert Scripts - -`fread()` doesn't directly support SQL `INSERT` scripts, but they can be processed via command-line tools. For example, given `insert_script.sql`: - -``` -INSERT INTO tbl VALUES (1, 'asd', 923123123, 'zx'); -INSERT INTO tbl VALUES (1, NULL, 923123123, 'zxz'); -INSERT INTO tbl VALUES (3, 'asd3', 923123123, NULL); -``` - -Use this command in R [link](https://stackoverflow.com/questions/32026398/transform-sql-insert-script-into-csv-format): - -```{r} -# 1. Create the SQL file programmatically -writeLines( -c( -"INSERT INTO tbl VALUES (1, 'asd', 923123123, 'zx');", -"INSERT INTO tbl VALUES (1, NULL, 923123123, 'zxz');", -"INSERT INTO tbl VALUES (3, 'asd3', 923123123, NULL);" -), -"insert_script.sql" -) -sql_lines = readLines("insert_script.sql") - -values_only = gsub("INSERT INTO tbl VALUES \\((.*)\\);", "\\1", sql_lines) - -dt_sql = fread(text = values_only, na.strings = "NULL") -print(dt_sql) - -file.remove("insert_script.sql") -``` - -- The `gsub()` function in R transforms each INSERT line into a comma-separated list of its values. - -- `na.strings = "NULL"` in fread is crucial: it tells fread to interpret the literal string `"NULL"` (output by awk for SQL NULLs) as R's NA value. - -- Quoted strings (e.g., 'asd') are preserved and read as character by `fread`. - -### 1.6 `integer64` Support +### 1.5 `integer64` Support By default, `fread` detects integers larger than 231 and reads them as `bit64::integer64` to preserve full precision. This behavior can be overridden in three ways: @@ -210,7 +172,7 @@ options(datatable.integer64 = "double") # Example: set globally to "double" getOption("datatable.integer64") ``` -### 1.7 Drop or Select Columns by Name or Position +### 1.6 Drop or Select Columns by Name or Position To save memory and improve performance, use `fread()`'s `select` or `drop` arguments to read only the columns you need. @@ -225,11 +187,11 @@ Key points: For details, see the manual page by running `?fread` in R. -### 1.8 Skip to a Sub-Table’s Header Row Using a Column Name Substring +### 1.7 Skip to a Sub-Table’s Header Row Using a Column Name Substring Use `skip="string"` in `fread` to search for a line containing a substring (typically from the column names, e.g., `skip="Date"`). Reading begins at the first matching line. This is useful for skipping metadata or selecting sub-tables in multi-table files. This feature is inspired by the `read.xls` function in the gdata package. -### 1.9 Automatic Quote Escape Detection (Including No-Escape) +### 1.8 Automatic Quote Escape Detection (Including No-Escape) `fread` automatically detects how quotes are escaped—including doubled ("") or backslash-escaped (\") quotes—without requiring user input. This is determined using a large sample of the data (see point 3), and validated against the entire file. From e01472df15098092fe69cad51373205c3c468488 Mon Sep 17 00:00:00 2001 From: venom1204 Date: Mon, 4 Aug 2025 15:14:29 +0530 Subject: [PATCH 10/15] Update vignettes/datatable-fread-and-fwrite.Rmd Co-authored-by: Benjamin Schwendinger <52290390+ben-schwen@users.noreply.github.com> --- vignettes/datatable-fread-and-fwrite.Rmd | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/vignettes/datatable-fread-and-fwrite.Rmd b/vignettes/datatable-fread-and-fwrite.Rmd index 81f681c44d..cfdbc1df33 100644 --- a/vignettes/datatable-fread-and-fwrite.Rmd +++ b/vignettes/datatable-fread-and-fwrite.Rmd @@ -83,8 +83,7 @@ print(dt_from_text) In many cases, `fread()` can automatically detect and decompress files with common compression extensions directly, without needing an explicit connection object or shell commands. This works by checking the file extension. **Supported extensions typically include:** -- `.gz` (gzip): Supported and works out of the box. -- `.xz` (xz): Supported and works out of the box. +- `.gz` / `.bz2` (gzip / bzip2): Supported and works out of the box. - `.zip` (ZIP archives, single file): Supported—`fread()` will read the first file in the archive if only one file is present. - `.tar` (tar archives, single file): Supported—`fread()` will read the first file in the archive if only one file is present. From 64b859e92baf4c27fd09a674f8e65209d7aa8d7a Mon Sep 17 00:00:00 2001 From: venom1204 Date: Mon, 4 Aug 2025 15:14:43 +0530 Subject: [PATCH 11/15] Update vignettes/datatable-fread-and-fwrite.Rmd Co-authored-by: Benjamin Schwendinger <52290390+ben-schwen@users.noreply.github.com> --- vignettes/datatable-fread-and-fwrite.Rmd | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/vignettes/datatable-fread-and-fwrite.Rmd b/vignettes/datatable-fread-and-fwrite.Rmd index cfdbc1df33..2cfdee474a 100644 --- a/vignettes/datatable-fread-and-fwrite.Rmd +++ b/vignettes/datatable-fread-and-fwrite.Rmd @@ -84,8 +84,7 @@ In many cases, `fread()` can automatically detect and decompress files with comm **Supported extensions typically include:** - `.gz` / `.bz2` (gzip / bzip2): Supported and works out of the box. -- `.zip` (ZIP archives, single file): Supported—`fread()` will read the first file in the archive if only one file is present. -- `.tar` (tar archives, single file): Supported—`fread()` will read the first file in the archive if only one file is present. +- `.zip` / `.tar` (ZIP / tar archives, single file): Supported—`fread()` will read the first file in the archive if only one file is present. > Note: If there are multiple files in the archive, `fread()` will fail with an error. From 799d0b34d41a92f9d25e73d9c47aff416bfd1cc0 Mon Sep 17 00:00:00 2001 From: venom1204 Date: Mon, 4 Aug 2025 11:30:29 +0000 Subject: [PATCH 12/15] added info in .rd --- man/fread.Rd | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/man/fread.Rd b/man/fread.Rd index 6071cf18bf..38352662f2 100644 --- a/man/fread.Rd +++ b/man/fread.Rd @@ -118,6 +118,15 @@ Currently, the \code{yaml} setting is somewhat inflexible with respect to incorp When \code{input} begins with http://, https://, ftp://, ftps://, or file://, \code{fread} detects this and \emph{downloads} the target to a temporary file (at \code{tempfile()}) before proceeding to read the file as usual. URLS (ftps:// and https:// as well as ftp:// and http://) paths are downloaded with \code{download.file} and \code{method} set to \code{getOption("download.file.method")}, defaulting to \code{"auto"}; and file:// is downloaded with \code{download.file} with \code{method="internal"}. NB: this implies that for file://, even files found on the current machine will be "downloaded" (i.e., hard-copied) to a temporary file. See \code{\link{download.file}} for more details. +\bold{Automatic Decompression:} + +In many cases, \code{fread} can automatically detect and decompress files with common compression extensions directly, without needing an explicit connection object or shell commands. This works by checking the file extension. + + \itemize{ + \item \code{.gz} and \code{.bz2} are supported out of the box. + \item \code{.zip} is also supported. If the archive contains a single data file, \code{fread} will read it. If the archive contains multiple files, \code{fread} will produce an error. + } + \bold{Shell commands:} \code{fread} accepts shell commands for convenience. The input command is run and its output written to a file in \code{tmpdir} (\code{\link{tempdir}()} by default) to which \code{fread} is applied "as normal". The details are platform dependent -- \code{system} is used on UNIX environments, \code{shell} otherwise; see \code{\link[base]{system}}. From f210a33021c7cce21800e07c38ca37ee4c01bc59 Mon Sep 17 00:00:00 2001 From: venom1204 Date: Tue, 5 Aug 2025 09:06:10 +0000 Subject: [PATCH 13/15] updated --- vignettes/datatable-fread-and-fwrite.Rmd | 13 ++++++------- 1 file changed, 6 insertions(+), 7 deletions(-) diff --git a/vignettes/datatable-fread-and-fwrite.Rmd b/vignettes/datatable-fread-and-fwrite.Rmd index 2cfdee474a..5bc7e229f4 100644 --- a/vignettes/datatable-fread-and-fwrite.Rmd +++ b/vignettes/datatable-fread-and-fwrite.Rmd @@ -216,20 +216,19 @@ From v1.10.6, `fread` resolves ambiguities more reliably across the entire file When data is written as strings (either inherently, like character columns, or by choice, like `dateTimeAs="ISO"`), `quote="auto"` (default) intelligently quotes fields: -**Contextual Quoting**: Only quotes fields if they contain the delimiter (`sep`), a double quote, or a newline. This ensures clean, RFC 4180-compliant CSVs. +**Contextual Quoting**:Fields are quoted only when necessary. This happens if they contain the delimiter `(sep)`, a double quote `(")`, a newline `(\n)`, a carriage return `(\r)`, or if the field is an empty string `("")`. Quoting the empty string is done to distinguish it from an NA value when the file is read. -**Bypassed for Direct Numeric Output**: If specific columns are written as their underlying numeric types (e.g., via `dateTimeAs="epoch"` for POSIXct, or if a user pre-converts Date to integer), then quoting logic is naturally bypassed for those numeric fields, contributing to efficiency. +**Bypassed for Direct Numeric Output**: If specific columns are written as their underlying numeric types (e.g., via `dateTimeAs="epoch"` for `POSIXct`, or if a user pre-converts Date to integer), then quoting logic is naturally bypassed for those numeric fields, contributing to efficiency. ```{r} dt_quoting_scenario = data.table( - text_field = c("Contains,a,comma", "Contains \"a quote\"", "Contains\na newline", "Clean_text"), - epoch_time = as.numeric(as.POSIXct("2023-10-26 14:35:00", tz = "GMT") + 1:4), # Already numeric - numeric_field = 1:4 + text_field = c("Contains,a,comma", "Contains \"a quote\"", "Clean_text", "", NA), + numeric_field = 1:5 ) -temp_quote_adv = tempfile(fileext = ".csv") +temp_quote_adv <- tempfile(fileext = ".csv") -# Quoting applies to text_field, but not to epoch_time or numeric_field fwrite(dt_quoting_scenario, temp_quote_adv) +# Note the output: the empty string is quoted (""), but the NA is not. cat(readLines(temp_quote_adv), sep = "\n") ``` From e7d5cfe332445faf865930a5b86d010b1588d568 Mon Sep 17 00:00:00 2001 From: venom1204 Date: Tue, 5 Aug 2025 17:47:02 +0000 Subject: [PATCH 14/15] updated cygwin part --- vignettes/datatable-fread-and-fwrite.Rmd | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/vignettes/datatable-fread-and-fwrite.Rmd b/vignettes/datatable-fread-and-fwrite.Rmd index 5bc7e229f4..ccd842e7f7 100644 --- a/vignettes/datatable-fread-and-fwrite.Rmd +++ b/vignettes/datatable-fread-and-fwrite.Rmd @@ -57,7 +57,7 @@ The `-v` option makes `grep` return all lines except those containing the string Look at this [example](https://stackoverflow.com/questions/36256706/fread-together-with-grepl/36270543#36270543) for more detail. -On Windows we recommend [Cygwin](https://www.cygwin.com/) (run one .exe to install) which includes the command line tools such as grep. In March 2016, Microsoft [announced](https://www.hanselman.com/blog/developers-can-run-bash-shell-and-usermode-ubuntu-linux-binaries-on-windows-10) they will include these tools in Windows 10 natively. On Linux and macOS, these tools have always been included in the operating system. You can find many examples and tutorials about command line tools online. We recommend [Data Science at the Command Line](https://www.oreilly.com/library/view/data-science-at/9781491947845/). +On Windows, command line tools like `grep` are available through various environments, such as Rtools, Cygwin, or the Windows Subsystem for Linux (WSL). On Linux and macOS, these tools are typically included with the operating system. #### 1.1.1 Reading directly from a text string @@ -225,7 +225,7 @@ dt_quoting_scenario = data.table( text_field = c("Contains,a,comma", "Contains \"a quote\"", "Clean_text", "", NA), numeric_field = 1:5 ) -temp_quote_adv <- tempfile(fileext = ".csv") +temp_quote_adv = tempfile(fileext = ".csv") fwrite(dt_quoting_scenario, temp_quote_adv) # Note the output: the empty string is quoted (""), but the NA is not. From 9bfb5d5453d5578c756a38cad7feef753745f2b2 Mon Sep 17 00:00:00 2001 From: venom1204 Date: Mon, 11 Aug 2025 08:30:43 +0000 Subject: [PATCH 15/15] added the links --- vignettes/datatable-fread-and-fwrite.Rmd | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/vignettes/datatable-fread-and-fwrite.Rmd b/vignettes/datatable-fread-and-fwrite.Rmd index ccd842e7f7..49cfa60db8 100644 --- a/vignettes/datatable-fread-and-fwrite.Rmd +++ b/vignettes/datatable-fread-and-fwrite.Rmd @@ -281,4 +281,15 @@ cat(readLines("out.csv"), sep = "\n") file.remove("out.csv") ``` +## 3. A Note on Performance + +While this vignette focuses on features and usability, the primary motivation for `fread` and `fwrite` is speed. The performance of `data.table`'s I/O is a topic of continuous benchmarking. + +For users interested in detailed, up-to-date performance comparisons, we recommend these external blog posts which use the `atime` package for rigorous analysis: + +- **[data.table asymptotic timings](https://tdhock.github.io/blog/2023/dt-atime-figures/)**: Compares `fread` and `fwrite` performance against other popular R packages like `readr` and `arrow`. +- **[Benchmarking data.table with polars, duckdb, and pandas](https://tdhock.github.io/blog/2024/pandas-dt/)**: Compares `data.table` I/O and grouping performance against leading Python libraries. + +These benchmarks consistently show that `fread` and `fwrite` are highly competitive and often state-of-the-art for performance in the R ecosystem. + *** \ No newline at end of file