I am trying to extract the name of the list I am passing to a function as a string. The string extracted must be stored within the same function (so I can use it during the same call).
Example:
my_function <- function(obj, arg = NULL) {
# obj is a list object that I pass to my_function()
obj_string <- ... # obj_string is the name of the list I have just passed to my_function
}
so, if I write my_function(list_name)
, obj_string
must store "list_name".
I tried with deparse(substitute(obj))
or deparse(substitute(Transform))
but they don't work.
I have also tried {{obj}}
but it won't work either.
CodePudding user response:
I finally managed to make it work myself (thanks to the other users who posted so far, I am going to test your answers too!)
as.character(as.list(match.call()[-1]$obj))
returns "list_name"
CodePudding user response:
We can use deparse/substitute
. We don't need to create an object inside
my_function <- function(obj, arg = NULL) {
deparse(substitute(obj))
}
-testing
> my_function(list_name)
[1] "list_name"
If we don't return anything. Just assign to an object and get the value or wrap with ()
to print into console
my_function <- function(obj, arg = NULL) {
obj_string <- deparse(substitute(obj))
}
-testing
> tmp <- my_function(list_name)
> tmp
[1] "list_name"
> > (my_function(list_name))
[1] "list_name"
CodePudding user response:
You need to either return
obj_string at the end of the function, or assign (<<-
) it to the environment:
my_function <- function(obj, arg = NULL) {
obj_string <- deparse(substitute(obj))
obj_string
}
#OR#
my_function <- function(obj, arg = NULL) {
obj_string <<- deparse(substitute(obj))
}