I am learning to generate loops. I have this function from "betapart" package:
beta.diversity <- beta.sample(x, index.family="Sorensen", sites= n, samples= n)
where
x: data frame, where rows are sites and columns are species.
index.family: family of dissimilarity indices, partial match of "sorensen" or "jaccard".
sites: number of sites for which multiple-site dissimilarities will be computed. If not specified, default is all sites. samples: number of repetitions. If not specified, default is 1.
What I need is to run the same function in a matrix, but increasing the sites one at a time (some matrix have 1000 sites)
I thought that with the "lapply" function it might work, but I can't think of how.
Thank you!
CodePudding user response:
See how a generic loop works:
fruits <- c("apple", "peach", "pear")
# Use the elements in a vector directly
for(fruit in fruits){
print(fruit)
}
# You can also use the index of each element
for(i in 1:length(fruits)){
print(fruits[i])
}
See how a generic lapply works:
lapply(fruits, print)
Get example data from the betapart
package:
library(betapart)
data(bbsData)
dat <- bbs2000[,1:10]
With a loop:
# Retain results
results <- list()
# Loop over each number of sites
allnsites = c(2:10)
for(i in 1:length(allnsites)){
beta.diversity <- beta.sample(dat, index.family="sorensen", sites= allnsites[i], samples= 1)
# Report number of sites in each iteration
beta.diversity$sites <- allnsites[i]
results[[i]] <- beta.diversity
}
With lapply()
:
lapply(allnsites, FUN = beta.sample, x = dat, index.family = "sorensen", samples = 1)