# Install install.packages("openxlsx") # LIBRARIES library(openxlsx) # INPUT THE PATH AND FILE NAME OF TARGET XLSX FilePath <- '~/Desktop/' # The name of files (i.e. nabc, mcdb, gentry, fia, cbc, bbs, fish and diatom) FileName <- "diatom" InputFileType<-".xlsx" FileID<-paste(FileName, InputFileType, sep = "") # READ DATA RawData <- read.xlsx(paste(FilePath, FileID, sep = ""), sheet = 1, colNames = F) # DETERMINE THE NUMBER OF COWS OF RawData DataSize <- sapply(RawData, NROW) GroupStart <- 2 GroupEnd <- 100 GroupNum <- 1 # DEFINE GROUP for(i in 3:DataSize[1]-1){ temp1 = 0 temp2 = 0 if (RawData[i,1] == RawData[i+1,1]) temp1 = 1 if (RawData[i,2] == RawData[i+1,2]) temp2 = 1 Index = temp1*temp2 if (Index == 0){ GroupEnd[GroupNum] = i GroupNum = GroupNum+1 GroupStart[GroupNum] = i+1 } } GroupEnd[GroupNum] = DataSize[1] # CALCULATION AND OUTPUT # output = list (RawData[1,1], RawData[1,2], "S", "At", "p", "R2") for (i in 1:GroupNum){ A_raw = RawData[GroupStart[i]:GroupEnd[i],4] A_raw = as.numeric(as.character(A_raw)) A=sort(A_raw, decreasing = T) S = GroupEnd[i]-GroupStart[i]+1 temp = c(1:S) x = c(1:S) y = c(1:S) At = sum(A) Ninf = 0 tempp1 = 0 tempp2 = 0 for (j in 1:S){ qr_ = A[j]/A[1] Ninf = Ninf + qr_ pi_ = A[j]/At x[j] = log(temp[j]) y[j] = log(qr_) tempp1 = tempp1 + x[j]*y[j] tempp2 = tempp2 + x[j]*x[j] } p = -1*tempp1/tempp2 sstotal = 0 ssresid = 0 my = mean(y) for (j in 1:S){ sy = -1*p*x[j] sstotal = sstotal + (y[j]-my)**2 ssresid = ssresid + (sy-y[j])**2 } ssreg = sstotal - ssresid R2 = ssreg/sstotal if (i == 1) { output = list (RawData[GroupStart[i],1], RawData[GroupStart[i],2], S, At, p, R2) } else { tempp = list(RawData[GroupStart[i],1], RawData[GroupStart[i],2], S, At, p, R2) output = rbind(output,tempp) } } # Output OutputFileName = "OutFile - " OutputFileName = paste(OutputFileName, FileName, sep="") OutputFileType = ".csv" OutputFileID = paste(OutputFileName, OutputFileType, sep="") colnames(output)<-c(RawData[1,1], RawData[1,2], "S", "At", "p", "R2") write.csv(output, paste(FilePath, OutputFileID, sep=""), row.names=F)