0

I am trying to store the source code of a function within a list, but I want to pass the function name to the list as a string.

This works:

hello_world <- function() print("Hello World")
my_list <- list(func = hello_world)
my_list
# $func
# function () 
# print("Hello World")

But I want to be able to pass the function name as a string. This of course just gives me the string:

my_list <- list(func = paste("hello", "world", sep = "_"))
my_list
# $func
# [1] "hello_world"

I have tried:

my_list <- list(func = as.formula(paste("hello", "world", sep = "_")))

Error: object of type 'closure' is not subsettable

and:

my_list <- list(func = call(paste("hello", "world", sep = "_")))
my_list
# $func
# hello_world()

If anyone has any idea about how I can make this work, I would truly appreciate it.

MichaelChirico
  • 33,841
  • 14
  • 113
  • 198
Kevin Burnham
  • 553
  • 2
  • 13
  • How would you like to be able to interact with this list? – MichaelChirico Aug 02 '16 at 21:46
  • 1
    E.g., why not just set the names of the list to the function name, the elements to the function? `my_list <- list(sum = sum, var = var)`; then we can do `my_list[["sum"]](1:4)`, etc. – MichaelChirico Aug 02 '16 at 21:46
  • Do you want `my_list <- list(func = function() paste("hello", "world", sep = "_"))`? – Weihuang Wong Aug 02 '16 at 21:47
  • `list_o_funs = setNames(list(function() print("Hello World")), "hello_world")` ? – Frank Aug 02 '16 at 21:49
  • Or maybe you want `mget("hello_world")`?? Also works as `my_list = mget(paste("hello", "world", sep = "_"))`. It would be nice if you could show what you mean by *"I want to pass the function name to the list as a string"*, and what you expect to happen when you do that. Based on "what you have tried", this seems most probably. – Gregor Thomas Aug 02 '16 at 21:51
  • ... in which case I would propose [How to call an object with a character variable as the same name](http://stackoverflow.com/q/9083907/903061) as a dupe. – Gregor Thomas Aug 02 '16 at 21:56
  • @Gregor - mget appears to do what I want. Thanks! If you want to make it an answer I can accept it. – Kevin Burnham Aug 02 '16 at 22:02

0 Answers0