From 28c50e2bb0182717b4e8b009bd3437101bd6c50e Mon Sep 17 00:00:00 2001 From: Alina Cherkas <51997505+alinacherkas@users.noreply.github.com> Date: Mon, 28 Oct 2024 23:37:33 +0100 Subject: [PATCH 1/2] fix(recode_char): correct replacements with `regex` and `default` --- R/recode_replace.R | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/R/recode_replace.R b/R/recode_replace.R index c9b369b9..5fc31ed7 100644 --- a/R/recode_replace.R +++ b/R/recode_replace.R @@ -156,9 +156,8 @@ recode_char <- function(X, ..., default = NULL, missing = NULL, regex = FALSE, } else { repfun <- function(y) if(is.character(y)) { z <- scv(y, 1L, y[1L], vind1 = TRUE) # Copy - y <- scv(y, nam[1L], default, set, TRUE) - scv(y, nam[1L], args[[1L]], TRUE) - for(i in seqarg[-1L]) scv(y, grepl(nam[i], z, ignore.case, FALSE, fixed), args[[i]], TRUE, vind1 = TRUE) + y <- scv(y, seq_along(y), default, set, vind1 = TRUE) # Initialize all to default + for(i in seqarg) scv(y, grepl(nam[i], z, ignore.case, FALSE, fixed), args[[i]], TRUE, vind1 = TRUE) y } else y } From 87e8464f986712b4cdc0cc5b623abcff5972e9f2 Mon Sep 17 00:00:00 2001 From: Alina Cherkas <51997505+alinacherkas@users.noreply.github.com> Date: Mon, 28 Oct 2024 23:41:23 +0100 Subject: [PATCH 2/2] test: add more tests for `recode_char` --- tests/testthat/test-recode-replace.R | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/tests/testthat/test-recode-replace.R b/tests/testthat/test-recode-replace.R index 6cf8d7d5..d9fa9985 100644 --- a/tests/testthat/test-recode-replace.R +++ b/tests/testthat/test-recode-replace.R @@ -56,7 +56,7 @@ set.seed(101) lmiss <- na_insert(letters) month.miss <- na_insert(month.name) char_dat <- na_insert(char_vars(GGDC10S)) - +char_nums <- c("-1", "1", "0", "2", "-2") options(warn = -1) test_that("recode_char works well", { @@ -93,6 +93,9 @@ test_that("recode_char works well", { expect_visible(recode_char(char_dat, saharan = "SSA", regex = TRUE, default = "n")) expect_visible(recode_char(char_dat, saharan = "SSA", regex = TRUE, default = "n", missing = "c")) + expect_equal(recode_char(char_nums, "-\\d+" = "negative", "0" = "zero", regex = T), c("negative", "1", "zero", "2", "negative")) + expect_equal(recode_char(char_nums, "0" = "zero", "-\\d+" = "negative", default = "positive", regex = T), c("negative", "positive", "zero", "positive", "negative")) + expect_equal(recode_char(char_nums, "-\\d+" = "negative", "0" = "zero", default = "positive", regex = T), c("negative", "positive", "zero", "positive", "negative")) }) set.seed(101)