user0981298732
user0981298732

Reputation: 1

How to save an element by string name?

I'd like to know how to save an element with save function by using the object name.

Here's an example:

my_object <- c("1","2")

What I'd like to do:

save("my_object", file = "my_object.rda")

So that the repository have all my elements.rda, and when I load them later, they have their original name.

Thanks!

Upvotes: 0

Views: 45

Answers (1)

Merijn van Tilborg
Merijn van Tilborg

Reputation: 5897

Most straightforward is use the object without quotes, however if you want to use a variable object name as a string you can do it with get. Just a demo, print suits as an example as well as saving your file.

my_object <- c("1", "2")

print(my_object)
[1] "1" "2"

print("my_object")
# "my_object"

print(get("my_object"))
# [1] "1" "2"

solution to write your file dynamically

save_me <- "my_object"
obj <- get(save_me)
save(obj, file = paste0(save_me, ".rda"))

Upvotes: 1

Related Questions