Reputation: 579
I have a function (not a function that I can modify though) that returns a ggplot2 object, and I would like to access some value of that object. However, the value is NULL
, but as soon as I print the object it becomes available.
Here is a minimal example that mimics the behaviour of that function
test_function <- function(test_arg){
ggplot() + annotate("text", x=0, y=0, label= test_arg)
}
Now I'd like to extract the value of the label that was set.
r$> result <- test_function("test")
r$> result$layers[[1]]$geom_params$label
NULL
However
r$> print(result)
r$> result$layers[[1]]$geom_params$label
[1] "test"
does work as intended.
How can I get the same result, but without actually printing the ggplot object?
Thanks!
Upvotes: 0
Views: 113
Reputation: 38023
I think it lives in the aes_params
part until the plot gets printed.
library(ggplot2)
test_function <- function(test_arg){
ggplot() + annotate("text", x=0, y=0, label= test_arg)
}
result <- test_function("test")
result$layers[[1]]$aes_params$label
#> [1] "test"
Created on 2021-03-19 by the reprex package (v0.3.0)
Upvotes: 1