Skip to content

Commit

Permalink
Respect the na argument in write_csv2
Browse files Browse the repository at this point in the history
We inadvertently removed the na handling by calling `format()`, which
changes all NAs to the characters "NA".

Fixes #928
  • Loading branch information
jimhester committed Nov 29, 2018
1 parent 6dcb5eb commit d52a177
Show file tree
Hide file tree
Showing 3 changed files with 19 additions and 3 deletions.
2 changes: 2 additions & 0 deletions NEWS.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
# readr 1.2.1.9000

* `write_csv2()` now properly respects the `na` argument (#928)

* Fixes compilation with multiple architectures on linux (#922).

* Fixes compilation with R < 3.3.0
Expand Down
11 changes: 10 additions & 1 deletion R/write.R
Original file line number Diff line number Diff line change
Expand Up @@ -226,7 +226,16 @@ stream_delim <- function(df, path, append = FALSE, bom = FALSE, ..., quote_escap
change_decimal_separator <- function(x, decimal_mark = ",") {
stopifnot(is.data.frame(x))
numeric_cols <- vapply(x, is.numeric, logical(1))
x[numeric_cols] <- lapply(x[numeric_cols], format, decimal.mark = decimal_mark)

format_seps <- function(x, decimal_mark) {
nas <- is.na(x)
x <- format(x, decimal.mark = decimal_mark)
x[nas] <- NA_character_
x
}

x[numeric_cols] <- lapply(x[numeric_cols], format_seps, decimal_mark)

x
}

Expand Down
9 changes: 7 additions & 2 deletions tests/testthat/test-write.R
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,8 @@ test_that("a literal NA is quoted", {
})

test_that("na argument modifies how missing values are written", {
df <- data.frame(x = c(NA, "x", "."))
expect_equal(format_csv(df, na = "."), "x\n.\nx\n\".\"\n")
df <- data.frame(x = c(NA, "x", "."), y = c(1, 2, NA))
expect_equal(format_csv(df, na = "."), "x,y\n.,1\nx,2\n\".\",.\n")
})

test_that("read_delim/csv/tsv and write_delim round trip special chars", {
Expand Down Expand Up @@ -142,6 +142,11 @@ test_that("write_csv2 and format_csv2 writes ; sep and , decimal mark", {
expect_equivalent(df, suppressMessages(read_csv2(filename)))
})

test_that("write_csv2 and format_csv2 writes NA appropriately", {
df <- tibble::data_frame(x = c(0.5, NA, 1.2), y = c("a", "b", NA))
expect_equal(format_csv2(df), "x;y\n0,5;a\nNA;b\n1,2;NA\n")
})

test_that("Can change the escape behavior for quotes", {
df <- data.frame(x = c("a", '"', ",", "\n"))

Expand Down

0 comments on commit d52a177

Please sign in to comment.