I have a performance issue in R. I have a function that iterates over a dataframe for different levels of "site" and "method". The function samples 1:1000 interactions (rows), converts these to matrices and calculates a value of connectance for each matrix. This is repeated n times. The function runs exactly as I want it, returning a dataframe with connectance values for 1 to 1000 interactions when repeated a small number of times. The problem is when I increase the number of repetitions (say to 100) the function runs progressively slower.
df <- read.table(text = "bird_sp plant_sp value site method
1 species_a plant_a 1 a m
2 species_a plant_a 1 a m
3 species_b plant_b 1 a m
4 species_b plant_b 1 a m
5 species_c plant_c 1 a m
6 species_a plant_a 1 b m
7 species_a plant_a 1 b m
8 species_b plant_b 1 b m
9 species_b plant_b 1 b m
10 species_c plant_c 1 b m
11 species_a plant_a 1 a f
12 species_a plant_a 1 a f
13 species_b plant_b 1 a f
14 species_b plant_b 1 a f
15 species_c plant_c 1 a f
16 species_a plant_a 1 b f
17 species_a plant_a 1 b f
18 species_b plant_b 1 b f
19 species_b plant_b 1 b f
20 species_c plant_c 1 b f", header = TRUE)
xDegrees <-function(df, size, numRep){
#Loading required library
require(bipartite)
#Creating vector of unique combinations
df <- within(df, {SiteMethod <- paste(site, method, sep = ":")})
#Creating empty dataframe
connectMatrix <- as.data.frame(matrix(rep(0,4), ncol = 4))
colnames(connectMatrix) <- c("Site","Method","Size","connectance")
#Beginning of matrix
k <- 1
#Beginning subsetting loop
for(i in 1:length(unique(df$SiteMethod))){
#subsetting dataset
dfSub <- subset(df, SiteMethod == unique(df$SiteMethod)[i])
#Storing site for matrix
site <- as.character(dfSub[1,]$site)
#Storing method for matrix
method <- as.character(dfSub[1,]$method)
for(l in 1:numRep){
#Beginning calculation loop
for(j in 1:length(size)){
#show progress
print(paste("S:M", i,j , "completed", sep = " "))
#The size being calculated
subSize <- size[j]
#generate random samples and convert to matrices
rows <- sample(1:nrow(dfSub), subSize, replace=T)
intlist <- dfSub[rows,]
mat <- with(intlist, tapply(value, list(plant_sp, bird_sp), sum))
mat[is.na(mat)] <- 0
#network level function to calculate connectance
con <- networklevel(mat, index = c("connectance"))
#Stitch matrix together
connectMatrix[k,] <- c(site, method, subSize, con)
#Update row
k <- k + 1
}
}
}
#Return complete matrix
return(connectMatrix)
}
#run the function. 1:1000 interactions, 100 reps
stuff <- xDegrees(df, size = 1:1000, numRep = 100)
Any ideas on how to speed this up?