Rename should (optionally) warn about mismatching keys #46

Closed
hadley opened this Issue Jun 29, 2011 · 3 comments

2 participants

@hadley
Owner

From Tim Bates:

a<-data.frame(x=1:5,y=1:5)
#   x y
# 1 1 1
# 2 2 2

rename(a, c(x= "y"))
# might be nice to warn the user they just duplicated a column name (if they ask for warnings)

rename(a, c(foo= "y"))
# might be nice to warn the user that nothing happened
@tbates

just commenting to watch... still desirable feature

@tbates

This code will check for names not being present in the original data, names being set more than once, and columns being set to the same value

rename <- function (x, replace) {
old_names <- names(x)
names_to_replace <- names(replace)
new_names_to_try <- unname(replace)

if(!all(names_to_replace %in% old_names)) {
warning("The following names did not appear in the dataframe:", paste(replace[!replace %in% old_names], collapse=","), "\nperhaps you already updated them")
}

if(anyDuplicated(names_to_replace)) {
err <- paste("You are trying to update the following names more than once:",
paste(names_to_replace[duplicated(names_to_replace)], collapse=""))
stop(err)
}

if(anyDuplicated(new_names_to_try)) {
err <- paste("You have the following duplicates in your replace list:",
paste(new_names_to_try[duplicated(new_names_to_try)], collapse=""))
stop(err)
}

new_names <- unname(replace)[match(old_names, names(replace))]

setNames(x, ifelse(is.na(new_names), old_names, new_names))
}

Here are some test cases

x <- c("a" = 1, "b" = 2, d = 3, 4)
rename(x, replace=c("d" = "c"))
rename(x, replace=c("e" = "c"))
rename(x, replace=c("a" = "c","d" = "c"))
rename(x, replace=c("a" = "c","a" = "c"))

@hadley
Owner

Fixed in #75.

@hadley hadley closed this Oct 5, 2012
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment