From 431cca9cda350e5e4f7ab9ed2802a141a0013cb4 Mon Sep 17 00:00:00 2001 From: mikefc Date: Tue, 2 Apr 2024 00:58:39 +0000 Subject: [PATCH] Handle 'NA' in factors written as strings. [fixed #35] --- src/R-yyjson-serialize.c | 2 ++ tests/testthat/test-factors.R | 20 ++++++++++++++++++++ 2 files changed, 22 insertions(+) create mode 100644 tests/testthat/test-factors.R diff --git a/src/R-yyjson-serialize.c b/src/R-yyjson-serialize.c index e9fca3e..56795cd 100644 --- a/src/R-yyjson-serialize.c +++ b/src/R-yyjson-serialize.c @@ -261,6 +261,8 @@ yyjson_mut_val *scalar_factor_to_json_val(SEXP factor_, R_xlen_t idx, yyjson_mu if (opt->factor == FACTOR_AS_INT) { val = scalar_integer_to_json_val(factor, doc, opt); + } else if (factor == NA_INTEGER) { + val = yyjson_mut_null(doc); } else { SEXP nms_ = getAttrib(factor_, R_LevelsSymbol); const char *nm = CHAR(STRING_ELT(nms_, factor - 1)); diff --git a/tests/testthat/test-factors.R b/tests/testthat/test-factors.R new file mode 100644 index 0000000..a68de19 --- /dev/null +++ b/tests/testthat/test-factors.R @@ -0,0 +1,20 @@ + +test_that("multiplication works", { + + # issue #35 + color <- c("red", "blue", NA, "red", "white") + color <- factor(color, levels=c("red", "blue")) + color + + expect_no_error({ + color_str <- yyjsonr::write_json_str(color, factor = 'integer') + }) + expect_identical('[1,2,null,1,null]', color_str) + + expect_no_error({ + color_str <- yyjsonr::write_json_str(color, factor = 'string') + }) + expect_identical('["red","blue",null,"red",null]', color_str) + +}) +