Home > database >  Retrieve the name of the last value as a character vector
Retrieve the name of the last value as a character vector

Time:09-22

I am trying to automate the naming of a ggplot output saved using ggsave()

When I create the following plot I am able to retrieve the name of the plot using a combination of the deparse and substitute functions if I state the plot name explicitly

# make the plot
df <- data.frame(x = 1:10, y = 1:10)   
my_plot <- ggplot(df, aes(x, y)) geom_point()

# generate the file name
filename <- paste0(deparse(substitute(my_plot)), ".jpg")
filename

However, I am trying to pass the plot name to the substitute function directly using without having to state it twice using .Last.value. This generates the incorrect result.

my_plot_name <- deparse(substitute(.Last.value))
my_plot_name 

## [1] ".Last.value"

How can I access the name of the last ggplot object (or any other object) to be saved without stating the name explicitly?

EDIT: To be specific, my desired output based on the above example and some pseudo code would look like this:

filename <- paste0(deparse(substitute(.Last.value)), ".jpg")
filename
    
## [1] "my_plot.jpg"

CodePudding user response:

You should be able to get it directly from the filename you're creating:

my_plot_name <- tools::file_path_sans_ext(filename)
my_plot_name

## [1] "my_plot"

Updated after edits:

.Last.value will only store the value, not the name of the variable that the value is being assigned into. First idea I'd have otherwise would be to check the names of variables in the environment to find which is equal to .Last.value. It seems to work in this simple case of your example:

my_plot <- ggplot(df, aes(x, y)) geom_point()
filename <- paste0(Filter(function(i) identical(get(i), .Last.value), ls()), ".jpg")
filename
## [1] "my_plot.jpg"
  • Related