Reputation: 3236
I am working on a package and want to make some functions that return very similar results. I thought it would be slick to assign the function names in a for-loop but I am not getting the desired results. The name updates each time but the value seems to only use the last value of i
.
I'm not sure what might be going on.
return_letter <- function(i){
letters[i]
}
for(i in 1:3) {
assign(paste0("fn_", i), function() return_letter(i))
}
fn_1() # expect "a", get "c"
fn_2() # expect "b", get "c"
fn_3() # expect "c", get "c"
rm(list = ls(pattern = "^fn_"))
For context, the package deals with color names and I want to return palettes for reds, blues, greens, etc.
Upvotes: 1
Views: 47
Reputation: 8572
A simple solution is creating the functions as string, parsing and then evaluating
for(i in 1:3)
eval(parse(text = paste0("fn_", i, " <- function()letters[", i, "]"))) #fixed mistake. Last i should be outside quotes.
However, it seems like quite an inefficient way of handling colour picking. The colourpicker
package, allows to selecting colours through a shiny widget. One might find interesting source code.
If the point is to store colours, for use within various function (such as shiny widgets), using an encapsulated environment or an object might be a safer or better way to go. Basically storing colours within a list as the colours are chosen for later. Using an R6 or S4 object (the prior is in most cases simpler and more intuitive to work with), would be one way to go in this case. (I'd suggest looking and trying the examples from ?R6::R6Class
in this case.)
Upvotes: 1