Search code examples
rfunctionveganreplicate

Create a function that replicates other function 100 times


I am trying to create a function that replicates 100 times other two functions and then calculate the average of the those values.

I have a matrix like this:

str(pref)
#num [1:9, 1:158] 4 9 15 6 7 8 6 11 11 4 ...
#- attr(*, "dimnames")=List of 2
# ..$ : NULL
# ..$ : chr [1:158] "V1" "V2" "V3" "V4" ...

I tried to reproduce it with this code (maybe not the best):

pref <- cbind(v = c(6,4,3,5,2,6), 
              c = c(5,6,7,4,2,5), 
              d= c(0,2,4,5,12,4))

It is a combination of the package vegan and SpadeR, the output o chao

library(vegan)
library("SpadeR")
library(tidyverse)
library(data.table)

pref[is.na(pref)] <- 0

chaox100 <- function(x, y){
  replicate(100, {
    subsample <-  rarefy(x, y)
    chao <- ChaoSpecies(subsample)
    df <- chao$Species_table
  })
}

If that helps, chao$Species_table is a matrix, so the function is replicating 100 times as it should but the output data is a mess. Look how is it:

I wanted to have like all the mean values of the all the data. I tried cbind, rbind, group_by(row.names), summarize_all.

str(test)
# num [1:9, 1:4, 1:100] 262 221 779 530 829 ...
# - attr(*, "dimnames")=List of 3
#  ..$ : chr [1:9] "    Homogeneous Model" "    Homogeneous (MLE)" "    Chao1 (Chao, 1984)" "    Chao1-bc" ...
#  ..$ : chr [1:4] "Estimate" "s.e." "95%Lower" "95%Upper"
#  ..$ : NULL

Solution

  • In order to run the function in the question and have it return the mean values, apply function mean to the output of replicate.

    chaox100 <- function(x, y){
      test <- replicate(100, {
        subsample <-  rarefy(x, y)
        chao <- ChaoSpecies(subsample)
        chao$Species_table
      })
      apply(test, MARGIN = 1:2, mean)
    }
    
    chaox100(pref, 70)
    #                              Estimate  s.e. 95%Lower 95%Upper
    #    Homogeneous Model            6.000 0.541    6.000    7.543
    #    Homogeneous (MLE)            6.467 0.795    6.047   10.595
    #    Chao1 (Chao, 1984)           6.000 0.541    6.000    7.543
    #    Chao1-bc                     6.000 0.541    6.000    7.543
    #    iChao1 (Chiu et al. 2014)    6.000 0.541    6.000    7.543
    #    ACE (Chao & Lee, 1992)       6.000 0.541    6.000    7.543
    #    ACE-1 (Chao & Lee, 1992)     6.000 0.541    6.000    7.543
    #    1st order jackknife          6.000 0.541    6.000    7.543
    #    2nd order jackknife          6.000 0.541    6.000    7.543
    #There were 50 or more warnings (use warnings() to see the first 50)