#### /packages/archive/2010/04.2010/04.30.2010/spacodi/R/resamp.3t.R

http://github.com/eastman/spacodiR
R | 55 lines | 46 code | 5 blank | 4 comment | 13 complexity | 97b91fd738f7bd137ab134087754c3f8 MD5 | raw file
``` 1resamp.3t <-
2function(obj, dmat=NULL) {
3	if(is.null(dmat))flag=TRUE else flag=FALSE
4	names.orig=names(obj)
5	names(obj)=seq(1:ncol(obj))
6	if(is.null(dmat)) {
7		dmat=as.data.frame(matrix(0,ncol(obj),ncol(obj)))
8		names(dmat)=names.orig
9		row.names(dmat)=names.orig
10	}
11	dmat=as.data.frame(as.matrix(dmat))
12	if(!all(names(dmat)%in%names.orig) || ncol(obj)!=ncol(dmat) || ncol(dmat)!=nrow(dmat))stop("Names in distance matrix do not correspond to plot names")
13	row.names(dmat)=names(obj)
14	names(dmat)=names(obj)
15
16# find all distances from plot.tt to plot.tt + some shifter value (e.g., '3' would be plot1 to plot4, plot10 to plot3, ... plotN to plotN+3)
17# tabulate these values and find the average distance from each plot to every plot+'shifter'
18	torus=rep(1:ncol(obj),2)
19	plus.array=array(dim=c(1,ncol(obj)))
20	torus.array=array(dim=c(ncol(obj), ncol(obj)))
21	for(plus in 1:ncol(obj)) {
22		for(tt in 1:ncol(torus.array)) {
23			from=tt
24			to=torus[tt+plus]
25			d.tt=dmat[from, to]
26			torus.array[tt,plus]=d.tt
27		}
28		plus.array[1,plus]=mean(torus.array[,plus],na.rm=TRUE)
29	}
30
31	plus.array=as.data.frame(plus.array)
32	names(plus.array)=names(obj)
33	plus.array=plus.array[,order(plus.array)]
34
35# randomly generate a value between 0 and maximum average distance from a plot to every other plot+'shifter'
36# shift species abundances by the randomly chosen 'shifter'
37	for(ss in 1:nrow(obj)){
38		if(!flag) {
39			shifter=as.numeric(names(plus.array))[min(which(plus.array>=runif(1,min=min(plus.array), max=max(plus.array))))]
40		} else {shifter = sample(as.numeric(names(plus.array)),1)}
41
42		t.array=array(dim=c(ncol(obj),2))
43		t.array[,1]=1:ncol(obj)
44		for(o in 1:ncol(obj)){
45			tt=torus[shifter+(o-1)]
46			t.array[tt,2]=obj[ss,o]
47		}
48		obj[ss,]=t.array[,2]
49	}
50	if(flag) message("Plots were assumed to be equidistant from one another.")
51	res=obj
52	names(res)=names.orig
53	return(res)
54}
55
```