user124123
user124123

Reputation: 1683

*apply in r to repeat a function

I've written a function that is a simulation, that outputs a vector of 100 elements, and I want to use the *apply functions to run the function many times and store the repeated output in a new vector for each time the simulation is run.

The function looks like:

J <- c(1:100)
species_richness <- function(J){
   a <- table(J)
   return(NROW(a))
}

simulation <- function(J,gens,ploton=FALSE,v=0.1){
    species_richness_output <- rep(NA,gens)
    for(rep in 1:gens){
        index1 <- sample(1:length(J),1)

        if(runif(1,0,1) < v){
           J[index1] <- (rep+100)
        } 
        else{
           index2 <- sample(1:length(J),1)
           while(index1==index2) {
               index2 <- sample(1:length(J),1)
           }
           J[index1] <- J[index2]
        }
        species_richness_output[rep] <- species_richness(J)
    }

    species_abundance <- function(J){
       a <- table(J)
       return(a)
    }

    abuntable <- species_abundance(J)
    print(abuntable)

    octaves <- function(abuntable){
       oct <- (rep(0,log2(sum(abuntable))))

       for(i in 1:length(abuntable)){
          oct2 <- floor(log2(abuntable[i])+1)
          oct[oct2] <- oct[oct2]+1
       }

       print(oct)
    }   

    # octaves(c(100,64,63,5,4,3,2,2,1,1,1,1))


    if(ploton==TRUE){
       hist(octaves(abuntable))
    }
    print(species_richness(J))

    return(J)
}

simulation(J, 10000,TRUE,v=0.1)

So that's my function, it takes J a vector I defined earlier, manipulates it, then returns: the newly simulated vector J of 100 elements a function called octave that categorises the new vector a histogram corresponding to the above "octave"

I have tried a number of variations: using lapply, mapply putting args=args_from_original_simulation

simulation_repeated <- c(mapply(list, FUN=simulation(args),times=10000))

but I keep getting an error with the match.fun part of the mapply function

Error in match.fun(FUN) : 
  'simulation(J, 10000, FALSE, 0.1)' is not a function, character or symbol

This is despite the simulation I have written showing as being saved as a function in the workspace.

Does anyone know what this error is pointing to?

Upvotes: 2

Views: 2626

Answers (1)

Matthew Lundberg
Matthew Lundberg

Reputation: 42639

In this line:

simulation_repeated <- c(mapply(list, FUN=simulation(args),times=10000))

You are not giving a function to mapply. You are (essentially) passing the result of calling simulation(args) and simulation does not return a function.

Upvotes: 1

Related Questions