Reputation: 883
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)
}}}
Upvotes: 0
Views: 921
Reputation: 646
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)
Upvotes: 1