0

I have a function that I'd like to run with a variety of parameters (see p_space in example). I can easily do this using a for loop. However, because I am planning to use parellel processing at a later date lapply seems like the way to go. Does anyone know how I can do this? My attempts don't seem to work at all!

example code:

as <- c(1,2)  # limit for K
bs <- c(3,4)
cs <- c(2,3)  # distribution of food sources ('random'/'clustered')

p_space <- list ()
for (a in as){
  for (b in bs){
    for (c in cs){
      p_space[[length(p_space)+1]] <- c(a,b,c)
    }
  }
}
made_up <- function(a, b, c){
  return(a * b * c)
}

My attempt to do this:

lapply(p_space, made_up(i) p_space[[i]])

My desired output is a dataframe/matrix/list with the results of the made_up function on all of the parameter sets in p_space.

How I would do this using for loops

 results <- list()

for (a in as){
  for (b in bs){
    for (c in cs){
      results[[length(results) + 1 ]] <- c(a*b*c,a,b,c)
    }}}
2
  • What is your expected output ? Commented Feb 22, 2018 at 17:24
  • added to the question. Sorry if it wasn't clear Commented Feb 22, 2018 at 17:28

1 Answer 1

1

Maybe pass a vector to made_up and then extract a,b and c?

made_up <- function(pvec){
  return(pvec[1]*pvec[2]*pvec[3])
}

lapply(p_space,made_up)
Sign up to request clarification or add additional context in comments.

2 Comments

amazing! This works. Do you know if there is a way that you can extract the parameter values that were used in each run as well?
actually, never mind I did this using return(list(pvec[1],pvec[2],pvec[3],pvec[1]*pvec[2],pvec[3])). Thanks for your help

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.