-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathCalculate_DetrendedStability.R
More file actions
72 lines (48 loc) · 1.97 KB
/
Calculate_DetrendedStability.R
File metadata and controls
72 lines (48 loc) · 1.97 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
############################################
# Calculate detrended ecosystem stability #
# following Tilman et al. 2006 #
############################################
# 1. for each plot, fit biomass ~ year
# 2. extract model residuals
# 4. calculate detrended stability as mean biomass/ detrended SD
# 3. calculate detrended SD as the sd of model residuals
require(reshape2)
require(dplyr)
require(tidyr)
require(stringr)
require(mgcv)
len_un<-function(x){length(unique(x))}
# prepare data
all<-read.delim("data.csv",sep=",",header=T)
all<-all[order(all$Study,all$Site,all$BlockUnique,all$PlotUnique,all$SppN,all$SppCode6),]
all$UniqueID<-paste(all$Study,"_",all$Site,"_",all$Block,"_",all$Plot)
all$UniqueID<-str_replace_all(all$UniqueID," ","")
all<-summarize(group_by(all, Study, Site, BlockUnique, PlotUnique, UniqueID, SppN, Year), Plot_Biomass=sum(Spp_Biomass))
all<-ungroup(all)
####################
# detrended SD #
####################
un_un<-unique(all$UniqueID) # vector of unique plot ids for loop
IDn<-seq(from=1, to=length(un_un))
unn<-cbind.data.frame(un_un,IDn)
colnames(unn)[1]<-"UniqueID"
all<-left_join(all, unn,by="UniqueID") # add unique plot id to year level data
nn<-len_un(all$IDn)
outt=c();
for(i in 1:nn){
test<-subset(all, all$IDn==(unique(all$IDn))[i])
cat("progress", i, sep=' ','\n')
modd<-lm(Plot_Biomass~Year, data=test)
test$resid<-residuals(modd, type="response")
detrend_sd<-sd(test$resid)
UniqueID<-unique(test$UniqueID)
outt[[i]]<-cbind.data.frame(UniqueID, detrend_sd)
}
synzz<-do.call(rbind.data.frame,outt)
# merge with big data
stab<-read.delim("data_II.csv",sep=",",header=T)
stab<-filter(stab,Site!="BIODEPTH_GR") # should get rid of site where we didn't have good trait coverage
stabb_out<-left_join(stab, synzz, by=c("UniqueID"))
# calculate de-treneded stability
stabb_out$Plot_TempStab_Detrend<-stabb_out$Plot_Biomassxbar/stabb_out$detrend_sd
write.table(stabb_out,"data_II.csv",sep=",",row.names=F)