Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP

Loading…

Fixes for mapvalues() and revalue() #97

Merged
merged 3 commits into from

2 participants

@wch
Collaborator
wch commented

This does the following :

  • mapvalues checks if the input is atomic.
  • revalue can handle NULL (it just returns NULL). This makes rename() able to handle empty vectors and lists (as it could do in the previous plyr release), which in turn fixes an issue in ggplot2::rename_aes().
  • Added tests for these things.
@hadley hadley merged commit 4ef25b6 into hadley:master
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Commits on Oct 9, 2012
  1. @wch
  2. @wch

    revalue: accept NULL input

    wch authored
  3. @wch

    Add tests for rename() with lists

    wch authored
This page is out of date. Refresh to see the latest.
View
5 R/helper-revalue.r
@@ -24,7 +24,7 @@
#' y <- factor(c("a", "b", "c", "a"))
#' revalue(y, c(a = "A", c = "C"))
revalue <- function(x, replace = NULL, warn_missing = TRUE) {
- if (!is.factor(x) && !is.character(x)) {
+ if (!is.null(x) && !is.factor(x) && !is.character(x)) {
stop("x is not a factor or a character vector.")
}
@@ -69,6 +69,9 @@ mapvalues <- function(x, from, to, warn_missing = TRUE) {
if (length(from) != length(to)) {
stop("`from` and `to` vectors are not the same length.")
}
+ if (!is.atomic(x)) {
+ stop("`x` must be an atomic vector.")
+ }
if (is.factor(x)) {
# If x is a factor, call self but operate on the levels
View
12 inst/tests/test-rename.r
@@ -26,3 +26,15 @@ test_that("Multiple names correctly changed", {
expect_equal(names(y), c("d", "e", "f"))
})
+
+test_that("Empty vectors and lists", {
+ rename(character(), c("c" = "f", "b" = "e", "a" = "d"))
+
+ expect_equal(names(y), c("d", "e", "f"))
+})
+
+test_that("Renaming lists", {
+ x <- list(a = 1, b = 2, c = 3)
+ y <- rename(x, c("c" = "f", "b" = "e", "a" = "d"))
+ expect_identical(y, list(d = 1, e = 2, f = 3))
+})
View
13 inst/tests/test-revalue.r
@@ -105,3 +105,16 @@ test_that("Mapping with ' ' and '$' in original and replacement works", {
expect_identical(revalue(fac2, c("A $1"="B $1")),
factor(c("B $1", "A2", "A3"), levels=c("A2", "B $1", "A3")))
})
+
+test_that("revalue and mapvalues only accept atomic vectors", {
+ expect_error(revalue(list(A=3), c("3"=30)))
+ expect_error(mapvalues(list(A=3), 3, 30))
+})
+
+test_that("revalue and mapvalues accept empty vectors and NULL", {
+ expect_identical(revalue(character(0), c("3"=30), warn_missing=FALSE), character(0))
+ expect_identical(mapvalues(character(0), 3, 30, warn_missing=FALSE), character(0))
+
+ expect_identical(revalue(NULL, c("3"=30), warn_missing=FALSE), NULL)
+ expect_identical(mapvalues(NULL, 3, 30, warn_missing=FALSE), NULL)
+})
Something went wrong with that request. Please try again.