Is there a “move” command in R (equivalent to <- followed by rm)?

This is one of those “what should be the function for these” questions. This is not such a big deal, but it is just annoying that every time I rename an object, I wonder if there is a better way.

Suppose that I use the created object for myself and understand that I would prefer not to capitalize it:

 # Create test data X <- runif(100) # Rename the object x <- X rm(X) 

Is there a one-way way to do this (which also avoids duplication for reasons of memory / speed)? Different packages have several commands named rename , but all of them work with elements in the list, and not with the list itself (or another object).

+4
source share
1 answer

I don’t know how to do this, but you can easily write your own function to do something in this direction. For example, it does this without any checks to make sure that the object exists or not or not the object with the name of what you want to rename.

 mv <- function(x, y){ x_name <- deparse(substitute(x)) y_name <- deparse(substitute(y)) assign(y_name, x, pos = 1) rm(list = x_name, pos = 1) invisible() } 

In some example, use

 > x <- 3 > x [1] 3 > y Error: object 'y' not found > mv(x, y) > x Error: object 'x' not found > y [1] 3 

Edit: for those who did not follow the link in the comments, here is a version written by Rolf Turner that does some checks to make sure that the object we want to move actually exists and asks us if we want to overwrite the existing one object, if the new name already has an object in it.

 mv <- function (a, b) { anm <- deparse(substitute(a)) bnm <- deparse(substitute(b)) if (!exists(anm,where=1,inherits=FALSE)) stop(paste(anm, "does not exist.\n")) if (exists(bnm,where=1,inherits=FALSE)) { ans <- readline(paste("Overwrite ", bnm, "? (y/n) ", sep = "")) if (ans != "y") return(invisible()) } assign(bnm, a, pos = 1) rm(list = anm, pos = 1) invisible() } 
+3
source

All Articles