Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

dplyr 0.3.0.2 rename() idiom unstable when reshape package is loaded

Tags:

r

dplyr

sessionInfo()
# R version 3.1.1 (2014-07-10)
# Platform: x86_64-apple-darwin10.8.0 (64-bit)
# 
# attached base packages:
#   [1] stats     graphics  grDevices utils     datasets  methods   base     
# 
# other attached packages:
#   [1] dplyr_0.3.0.2
# 
# loaded via a namespace (and not attached):
#   [1] assertthat_0.1 DBI_0.3.1      lazyeval_0.1.9 magrittr_1.0.1 parallel_3.1.1 Rcpp_0.11.3   
# [7] tools_3.1.1  

when only dplyr 0.3.0.2 was loaded, the default rename idiom worked.

packageVersion("dplyr")
# [1] ‘0.3.0.2’
iris[1:10,] %>% rename(petal_length = Petal.Length)
#    Sepal.Length Sepal.Width petal_length Petal.Width Species
# 1           5.1         3.5          1.4         0.2  setosa
# 2           4.9         3.0          1.4         0.2  setosa

when library(reshape) was loaded, the idiom did not seem to work

# other attached packages:
#   [1] reshape_0.8.5 dplyr_0.3.0.2
# 
# loaded via a namespace (and not attached):
#   [1] assertthat_0.1   chron_2.3-45     data.table_1.9.5 DBI_0.3.1        lazyeval_0.1.9  
# [6] magrittr_1.0.1   parallel_3.1.1   plyr_1.8.1       Rcpp_0.11.3      reshape2_1.4    
# [11] stringr_0.6.2    tidyr_0.1        tools_3.1.1     

iris[1:10,] %>% rename(petal_length = Petal.Length)
# Error in rename(`iris[1:10, ]`, petal_length = Petal.Length) : 
#   unused argument (petal_length = Petal.Length)

and need to resort to the code below

iris[1:10,] %>% rename(c("Petal.Length" = "petal_length"))
#    Sepal.Length Sepal.Width petal_length Petal.Width Species
# 1           5.1         3.5          1.4         0.2  setosa
# 2           4.9         3.0          1.4         0.2  setosa

Is this a bug?

like image 436
KFB Avatar asked Oct 14 '14 22:10

KFB


2 Answers

When you have two or more packages loaded that contain functions with the same name, you'll need to use the double-colon operator :: to get the version of the function from the package that was not the last loaded package (hopefully that makes sense).

So in terms of these two packages, that means dplyr::rename() to use the dplyr version, or reshape::rename() to use the reshape version, depending on the arrangement of the packages on the search path.

Since you loaded the reshape package after you loaded the dplyr package, you need dplyr::rename() to use the rename() function from the dplyr package. rename() alone dispatches to the reshape version in this case.

iris[1:10,] %>% dplyr::rename(petal_length = Petal.Length)

should do the trick.

like image 59
Rich Scriven Avatar answered Oct 27 '22 00:10

Rich Scriven


I recommend data.table::setnames function.

iris %>% 
data.table::setnames(
    old = "Petal_length",
    new = "petal_length") %>% 
  head
like image 39
Jiaxiang Avatar answered Oct 26 '22 23:10

Jiaxiang