Skip to content
This repository
Browse code

Merge pull request #97 from wch/mapvalues-fixes

Fixes for mapvalues() and revalue()
  • Loading branch information...
commit 4ef25b61145cd4b93af4598ebc1eda4b5e46cb4f 2 parents 1290d86 + 0e9bae5
Hadley Wickham authored October 09, 2012
5  R/helper-revalue.r
@@ -24,7 +24,7 @@
24 24
 #' y <- factor(c("a", "b", "c", "a"))
25 25
 #' revalue(y, c(a = "A", c = "C"))
26 26
 revalue <- function(x, replace = NULL, warn_missing = TRUE) {
27  
-  if (!is.factor(x) && !is.character(x)) {
  27
+  if (!is.null(x) && !is.factor(x) && !is.character(x)) {
28 28
     stop("x is not a factor or a character vector.")
29 29
   }
30 30
 
@@ -69,6 +69,9 @@ mapvalues <- function(x, from, to, warn_missing = TRUE) {
69 69
   if (length(from) != length(to)) {
70 70
     stop("`from` and `to` vectors are not the same length.")
71 71
   }
  72
+  if (!is.atomic(x)) {
  73
+    stop("`x` must be an atomic vector.")
  74
+  }
72 75
 
73 76
   if (is.factor(x)) {
74 77
     # If x is a factor, call self but operate on the levels
12  inst/tests/test-rename.r
@@ -26,3 +26,15 @@ test_that("Multiple names correctly changed", {
26 26
 
27 27
   expect_equal(names(y), c("d", "e", "f"))
28 28
 })
  29
+
  30
+test_that("Empty vectors and lists", {
  31
+  rename(character(), c("c" = "f", "b" = "e", "a" = "d"))
  32
+
  33
+  expect_equal(names(y), c("d", "e", "f"))
  34
+})
  35
+
  36
+test_that("Renaming lists", {
  37
+  x <- list(a = 1, b = 2, c = 3)
  38
+  y <- rename(x, c("c" = "f", "b" = "e", "a" = "d"))
  39
+  expect_identical(y, list(d = 1, e = 2, f = 3))
  40
+})
13  inst/tests/test-revalue.r
@@ -105,3 +105,16 @@ test_that("Mapping with ' ' and '$' in original and replacement works", {
105 105
   expect_identical(revalue(fac2, c("A $1"="B $1")),
106 106
                    factor(c("B $1", "A2", "A3"), levels=c("A2", "B $1", "A3")))
107 107
 })
  108
+
  109
+test_that("revalue and mapvalues only accept atomic vectors", {
  110
+  expect_error(revalue(list(A=3), c("3"=30)))
  111
+  expect_error(mapvalues(list(A=3), 3, 30))
  112
+})
  113
+
  114
+test_that("revalue and mapvalues accept empty vectors and NULL", {
  115
+  expect_identical(revalue(character(0), c("3"=30), warn_missing=FALSE), character(0))
  116
+  expect_identical(mapvalues(character(0), 3, 30, warn_missing=FALSE), character(0))
  117
+
  118
+  expect_identical(revalue(NULL, c("3"=30), warn_missing=FALSE), NULL)
  119
+  expect_identical(mapvalues(NULL, 3, 30, warn_missing=FALSE), NULL)
  120
+})

0 notes on commit 4ef25b6

Please sign in to comment.
Something went wrong with that request. Please try again.