0

Given the following function which returns a function

get_function <- \(model) {
  meanlog <- model[['Mean']]
  sdlog <- model[['SD']]
  \(x){ dlnorm(x, 
               meanlog = meanlog, 
               sdlog = sdlog)
  }
}

When I use the get_function as follow:

func <- distributions[['866064']] |> get_function()

func return the correct function. All work as expected, Great!

However, when I try to use the get_function in a for loop, like so:

output <- NULL
for(product in names(distributions)) {
  output[[product]] <- distributions[[product]] |> get_function()
}

All the functions loaded in the output list are the same, where they should be different because the model associated with each product in the distributions list is different.

What am I doing wrong? How can I get the correct function loaded into the output list based on the different models in the distributions list?

  • 2
    It's easier to help you if you include a simple [reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) with sample input and desired output that can be used to test and verify possible solutions. Please define the `distributions` variable here. – MrFlick Jul 26 '21 at 19:16

1 Answers1

1

We could initialize 'output' as a list instead of NULL

output <- vector('list', length(distributions))
names(output) <- names(distributions)

In the OP's loop, the assignment was done with a different object i.e. ouput instead of output

akrun
  • 874,273
  • 37
  • 540
  • 662
  • still does not really solve the problem. The output function loaded into each item in output list is the same and should be different – Flippie Coetser Jul 26 '21 at 19:14
  • @FlippieCoetser now, it does with the update – akrun Jul 26 '21 at 19:15
  • was a type error in stack overflow. real code does use output – Flippie Coetser Jul 26 '21 at 19:15
  • @FlippieCoetser can you `print(product)` it should be the same as you showed. I am guessing that if it is a dataframe, its name got changed by appending `X` as prefix – akrun Jul 26 '21 at 19:16
  • print(product) give the correct list. When I print(distributions[[product]][['Mean']]) and print(distributions[[product]][['SD']]) I also get the correct values. – Flippie Coetser Jul 26 '21 at 19:18
  • @FlippieCoetser can you try the code I showed – akrun Jul 26 '21 at 19:19
  • > output <- vector('list', ncol(distributions)) Error in vector("list", ncol(distributions)) : invalid 'length' argument. distributions is not a dataframe. It is a named list – Flippie Coetser Jul 26 '21 at 19:21
  • @FlippieCoetser if you can update your post with a small example for testing, that would be useufl – akrun Jul 26 '21 at 19:23