How do I rename an R object?
Renaming an object and the colnames within it is a two step process:
SPY <- GSPC # assign the object to the new name (creates a copy)
colnames(SPY) <- gsub("GSPC", "SPY", colnames(SPY)) # rename the column names
Otherwise, the getSymbols function allows you to not auto assign, in which case you could skip the first step (you will still need to rename the columns).
SPY <- getSymbols("^GSPC", auto.assign=FALSE)
Comment from @backlin
R employs so-called lazy evaluation. An effect of that is that when you "copy" SPY <- GSPC
you do not actually allocate new space in the memory for SPY
. R knows the objects are identical and only makes a new copy in the memory if one of them is modified (i.e. when they are no longer the identical, e.g. when you change the column names on the following line). So by doing
SPY <- GSPC
rm(GSPC)
colnames(SPY) <- gsub("GSPC", "SPY", colnames(SPY))
you never really copy GSPC
but merely give it a new name (SPY
) and then tell R to forget the first name (GSPC
). When you then change the column names you do not need to create a new copy of SPY
since GSPC
no longer exists, meaning you have truly renamed the object without creating intermediate copies.
Rename objects in environment r
If you can’t assign them directly with the correct name, then the easiest is to replace the environment by a new one. If you absolutely need to preserve the environment (because it’s referenced elsewhere), you can replace its contents using the same trick:
objs = mget(ls(env), env)
rm(list = ls(env), envir = env)
list2env(setNames(objs, new_names), env)
The relevant part here is the last parameter to list2env
: if you leave it off, this just creates a new environment. If you specify an existing environment, the names are added to that instead.
This code will leave hidden names (i.e. names starting with .
) untouched — to change this, provide the all.names
argument to ls
, or use names
.
How to rename a variable in R without copying the object?
R is smart enough not to make a copy if the variable is the same, so just go ahead, reassign and rm()
the original.
Example:
x <- 1:10
tracemem(x)
# [1] "<0000000017181EA8>"
y <- x
tracemem(y)
# [1] "<0000000017181EA8>"
As we can see both objects point to the same address. R makes a new copy in the memory if one of them is modified, i.e.: 2 objects are not identical anymore.
# Now change one of the vectors
y[2] <- 3
# tracemem[0x0000000017181ea8 -> 0x0000000017178c68]:
# tracemem[0x0000000017178c68 -> 0x0000000012ebe3b0]:
tracemem(x)
# [1] "<0000000017181EA8>"
tracemem(y)
# [1] "<0000000012EBE3B0>"
Related post: How do I rename an R object?
Using an object to rename a variable in R
You can use {{new_name}}
new_name <- paste("New","Name")
as.data.frame(state.x77) %>%
rename({{new_name}}:=Population) %>%
head()
New Name Income Illiteracy Life Exp Murder HS Grad Frost Area
Alabama 3615 3624 2.1 69.05 15.1 41.3 20 50708
Alaska 365 6315 1.5 69.31 11.3 66.7 152 566432
Arizona 2212 4530 1.8 70.55 7.8 58.1 15 113417
Arkansas 2110 3378 1.9 70.66 10.1 39.9 65 51945
California 21198 5114 1.1 71.71 10.3 62.6 20 156361
Colorado 2541 4884 0.7 72.06 6.8 63.9 166 103766
Alternatively, you can do this
state = as.data.frame(state.x77)
colnames(state)[which(colnames(state)=="Population")] <- new_name
head(state)
New Name Income Illiteracy Life Exp Murder HS Grad Frost Area
Alabama 3615 3624 2.1 69.05 15.1 41.3 20 50708
Alaska 365 6315 1.5 69.31 11.3 66.7 152 566432
Arizona 2212 4530 1.8 70.55 7.8 58.1 15 113417
Arkansas 2110 3378 1.9 70.66 10.1 39.9 65 51945
California 21198 5114 1.1 71.71 10.3 62.6 20 156361
Colorado 2541 4884 0.7 72.06 6.8 63.9 166 103766
How to rename objects in R based on function arguments?
In R, you can't return a vector called something. If you want a vector called vector_1
to just appear after you call the function without having to store it anywhere, you need to use assign
or the <<-
operator inside the function. This usually isn't a good idea.
However, it is a good idea to have named vectors inside a list, and this can be done simply without using a loop at all:
indexed_vector <- function(df, i) setNames(as.list(df[i]), paste0("vector_", i))
df <- data.frame(a = 1:3, b = 4:6, c = 7:9, d = 10:12)
indexed_vector(df, 1:3)
#> $vector_1
#> [1] 1 2 3
#>
#> $vector_2
#> [1] 4 5 6
#>
#> $vector_3
#> [1] 7 8 9
Created on 2020-06-11 by the reprex package (v0.3.0)
r - Rename R object while save()-ing it
This proved to be a little trickier that I expected. I'll be interested to see what others come up with, and also what any objections to my solution may be.
saveit <- function(..., file) {
x <- list(...)
save(list=names(x), file=file, envir=list2env(x))
}
foo <- 1
saveit(bar=foo, file="hi.Rdata")
Name or rename list object in R with str_c() or paste()
Use either setNames
or
append(all_output, setNames(list(params), str_c("this_", "does_", "not_", "work")))
-output
$this_works_fine
# A tibble: 3 × 2
col1 col2
<dbl> <chr>
1 1 a
2 2 b
3 3 c
$this_does_not_work
# A tibble: 3 × 2
col1 col2
<dbl> <chr>
1 1 a
2 2 b
3 3 c
or use lst
from dplyr
with :=
append(all_output, lst(!!str_c("this_", "does_", "not_", "work") := params))
-output
$this_works_fine
# A tibble: 3 × 2
col1 col2
<dbl> <chr>
1 1 a
2 2 b
3 3 c
$this_does_not_work
# A tibble: 3 × 2
col1 col2
<dbl> <chr>
1 1 a
2 2 b
3 3 c
R rename an object / data.frame without intermediary object
@landroni answered the question. Here's an example showing that this is indeed how R works.
# copy an object to a new variable name, no change in memory usage
rm(list=ls())
gc()
memory.size()
# [1] 40.15
big.obj <- seq(1e7)
memory.size()
# [1] 78.34
big.obj.renamed <- big.obj
memory.size()
# [1] 78.34
rm(big.obj)
memory.size()
# [1] 78.34
# if the first variable is modified, however, you see the evidence of a hard copy
rm(list=ls())
gc()
memory.size()
# [1] 40.15
big.obj <- seq(1e7)
memory.size()
# [1] 78.34
big.obj.renamed <- big.obj
memory.size()
# [1] 78.34
big.obj[1] <- 2 # modifying the original forces hard copy
memory.size()
# [1] 192.8
Rename objects in for loop in R
Another option is to use assign
for ( i in 1:10) {
assign(paste0("plot", i), ggplot(data, aes(x=data[,i], fill=Group)) +
geom_histogram(binwidth=200, alpha=.5, position="dodge") )
}
This will create each plot as a different object (plot1
, plot2
, plot3
... ) in your global environment
Related Topics
How to Automatically Include All 2-Way Interactions in a Glm Model in R
Change Color of Leaflet Marker
R Convert Between Zoo Object and Data Frame, Results Inconsistent for Different Numbers of Columns
Convert Matrix to Three Column Data.Frame
Unnest a List Column Directly into Several Columns
Run R Script from .Bat (Batch File)
Using Annotate to Add Different Annotations to Different Facets
Scatterplot with Color Groups - Base R Plot
How to Append Data from a Data Frame in R to an Excel Sheet That Already Exists
R Not Finding Package Even After Package Installation
Logistic Regression - Defining Reference Level in R
Disregarding Simple Warnings/Errors in Trycatch()
Create a Formula in a Data.Table Environment in R
How to Display Verbatim Inline R Code with Backticks Using Rmarkdown
How to Write an R Function That Evaluates an Expression Within a Data-Frame