we do have a sample script available that helps you run logistic regression using the R statistical package right from inside ArcMap. here.
The "clustTool" library is in fact not available for versions of R > 2.12 however, the "Design" library has been folded into the "rms" (Regression Modeling Strategies) library without change in function names. The clustTool library is only required for clustering models. The implementation of logistic regression uses the rms library so, if you only need the logistic implementation you should be fine. I think that I will rewrite the code and post a new version with some new bells-and-whistles. Hopefully ESRI will not have a problem with this.
versionBool = checkRVersion(2, 14) if (versionBool){ library(rms) }else{ require(Design) }
require(rms)
This is not my toolbox, I was just planning on updating the clustering functionality. In taking a quick look at the R code ESRI has built in a very specific (2.14) version dependency. Since this condition is false then it is trying to add the depreciated library "Design". You can fix this by opening the file"LogitWithR.r", located in the Scripts directory, in a text editor.Delete these linesversionBool = checkRVersion(2, 14) if (versionBool){ library(rms) }else{ require(Design) } And replace withrequire(rms)
You are using an older version of the toolbox. Download the "more current" 10-10.1 compliant version here:http://www.arcgis.com/home/item.html?id=a5736544d97a4544aa47d06baf910f6d
#################################################### # USER ARGUMENTS #################################################### # SET WORKING DIRECTORY setwd("D:/TMP") # SET VARIABLE NAMES dependentVar = "SppDen" independentVars = c("Var1","Var2","Var3") usePenalty=TRUE # USE PENALTY InShp="MyShape" # IN SHAPEFILE (NO .shp NEEDED) OutShp="LogitModel" # OUT SHAPEFILE (NO .shp NEEDED) diagTable = "Diag.csv" # DIAGNOSTIC TABLE coefTable = "Coef.csv" # COEFFICENT TABLE #################################################### # START MODEL #################################################### require(sp) require(rgdal) require(rms) # READ SHAPEFILE shp <- readOGR(getwd(), InShp) # CHECK VARIABLE NAMES if ( is.na(match(dependentVar,names(shp@data))) ) stop("Dependent Variable not present in data") xNames <- intersect(independentVars,names(shp@data)) if (length(xNames) < length(independentVars)) stop("Mismatch in Independent Variable Names") # CREATE FORMULA form=as.formula(paste(dependentVar, paste(independentVars, collapse='+'), sep='~')) # LOGISTIC REGRESSION WITH AIC fit <- lrm(form, data=shp@data, x = TRUE, y = TRUE) bf <- pentrace(fit, seq(.2,1,by=.05)) if (usePenalty) { pen = bf$penalty } else { pen = 0.0 } allPens = bf$results.all[,1] allAICs = bf$results.all[,3] for (i in 1:length(allPens)){ penValue = allPens if (penValue == pen){ aic = allAICs } } if (usePenalty){ fit = update(fit, penalty=bf$penalty) } # RESIDUAL ERROR res <- residuals.lrm(fit) resSTD <- (res - mean(res)) / sqrt(var(res)) # ADD RESIDUALS, STANDARDIZED RESIDUALS AND PROBABILITIES shp@data <- data.frame(shp@data,Residual=res, StdResid=resSTD, Probs=predict(fit,shp@data[,rownames(fit$var)[-1]], type="fitted") ) # WRITE SHAPEFILE writeOGR(shp, dsn=getwd(), OutShp, driver="ESRI Shapefile", check_exists=TRUE, overwrite_layer=TRUE) # WRITE COEFFICENT AND DIAGNOSTIC TABLES allIndVars = c("Intercept") allIndVars = append(allIndVars, independentVars) k = length(allIndVars) d = matrix(0, k, 4) d[,1] = fit$coefficients d[,2] = sqrt(diag(fit$var)) d[,3] = d[,1] / d[,2] d[,4] = pnorm(abs(d[,3]), lower.tail = FALSE) * 2.0 coefList = list("Variable"=allIndVars, "Coef"=d[,1], "StdError"=d[,2], "Wald"=d[,3], "Prob"=d[,4]) coefFrame = data.frame(coefList) write.csv(coefFrame, coefTable, row.names=FALSE) daigFrame <- data.frame(Names=c(names(fit$stats),"PEN","AIC"), Value=c(as.vector(fit$stats), pen, aic)) write.csv(daigFrame, diagTable, row.names=FALSE)
############################################################################## # PROGRAM: LogitRegression (logistic regression called form ArcGIS) # USE: LOGISTIC (BIONOMIAL) REGRESSION # REQUIRES: R > 2.15.0, rms # # ARGUMENTS: # ldata DATAFRAME OBJECT CONTANING VARIABLES # y RESPONSE VARIABLE IN ldata # x INDEPENDENT VARIABLES(S) IN ldata # penelty APPLY REGRESSION PENELTY (TRUE/FALSE) # ... ADDITIONAL ARGUMENTS PASSED TO lrm # # VALUE: # A LIST OBJECT CONTANING OBJECTS: # model lrm MODEL OBJECT # diagTable DATAFRAME OF REGRESSION DIAGNOSTICS # coefTable DATAFRAME OF REGRESSION COEFFICENTS # Residuals DATAFRAME OF RESIDUALS AND STANDARDIZED RESIDUALS # # REFERENCES: # Le Cessie S, Van Houwelingen JC: Ridge estimators in logistic regression. # Applied Statistics 41:191�??201, 1992. # # Shao J: Linear model selection by cross-validation. JASA 88:486�??494, 1993. # # EXAMPLES: # require(sp) # require(rms) # # data(meuse) # coordinates(meuse) <- ~x+y # meuse@data <- data.frame(DepVar=rbinom(dim(meuse)[1], 1, 0.5), meuse@data) # names(meuse@data) # # # RUN Bernoulli Trials TEST # binom.test( c(length(meuse[meuse@data$DepVar == 1 ,]$DepVar), # length(meuse[meuse@data$DepVar == 0 ,]$DepVar)), 0.65) # # # RUN LOGISTIC MODEL # lmodel <- LogitRegression(meuse@data, y="DepVar", x=c("dist","cadmium","copper")) # lmodel$model # lmodel$diagTable # lmodel$coefTable # # # ADD RESIDUALS, STANDARDIZED RESIDUALS AND PROBABILITIES # meuse@data <- data.frame(meuse@data, Residual=lmodel$Residuals[,1], # StdResid=lmodel$Residuals[,2], # Probs=predict(lmodel$model,meuse@data[,rownames(lmodel$model$var)[-1]], # type="fitted") ) # # # PLOT PROBABILITIES # library(lattice) # trellis.par.set(sp.theme()) # spplot(meuse, c("Probs")) # # CONTACT: # Jeffrey S. Evans # Senior Landscape Ecologist # The Nature Conservancy - Central Science # Adjunct Assistant Professor # Zoology and Physiology # University of Wyoming # Laramie, WY # (970)672-6766 # jeffrey_evans@tnc.org ###################################################################################### LogitRegression <- function (ldata, y, x, penalty=TRUE, ...) { if (!require (rms)) stop("sp PACKAGE MISSING") if ( is.na(match(y,names(ldata))) ) stop("Dependent Variable not present in data") xNames <- intersect(x,names(ldata)) if (length(xNames) < length(x)) stop("Mismatch in Independent Variable Names") form=as.formula(paste(y, paste(x, collapse='+'), sep='~')) fit <- lrm(form, data=ldata, x=TRUE, y=TRUE, ...) bf <- pentrace(fit, seq(0.2,1,by=0.05)) if (penalty) { pen = bf$penalty } else { pen = 0.0 } allPens=bf$results.all[,1] allAICs=bf$results.all[,3] for (i in 1:length(allPens)){ penValue=allPens if (penValue == pen){ aic = allAICs } } if (penalty){ fit = update(fit, penalty=bf$penalty) } res <- residuals.lrm(fit) resSTD <- (res - mean(res)) / sqrt(var(res)) allIndVars <- c("Intercept") allIndVars <- append(allIndVars, x) k <- length(allIndVars) d <- matrix(0, k, 4) d[,1] <- fit$coefficients d[,2] <- sqrt(diag(fit$var)) d[,3] <- d[,1] / d[,2] d[,4] <- pnorm(abs(d[,3]), lower.tail = FALSE) * 2.0 coefList=list("Variable"=allIndVars, "Coef"=d[,1], "StdError"=d[,2], "Wald"=d[,3], "Prob"=d[,4]) coefFrame=data.frame(coefList) diagFrame=data.frame(Names=c(names(fit$stats),"PEN","AIC"), Value=c(as.vector(fit$stats), pen, aic)) return(list(model=fit, diagTable=diagFrame, coefTable=coefFrame, Residuals=data.frame(res=res,resSTD=resSTD))) } ### Version check Rv <- paste(round(as.numeric(R.version$major),digits=0), as.numeric(R.version$minor),sep=".") if (Rv < 2.14) stop("NEED TO UPGRADE VERSION OF R TO >= 2.14") #### Load required packages print("Loading Libraries....") if (!require(rms)) stop("rms PACKAGE MISSING") if (!require(sp)) stop("sp PACKAGE MISSING") if (!require(rgdal)) stop("rgdal PACKAGE MISSING") if (!require(foreign)) stop("foreign PACKAGE MISSING") #### Get Arguments Args = commandArgs() inputFC = sub(".shp", "", Args[5], ignore.case=TRUE) outputFC = sub(".shp", "", Args[6], ignore.case=TRUE) dependentVar = Args[7] independentVarString = Args[8] usePenalty = as.integer(Args[9]) usePenalty <- usePenalty == 1 coefTable = sub(".csv", "", Args[10], ignore.case=TRUE) diagTable = sub(".csv", "", Args[11], ignore.case=TRUE) print(paste(commandArgs(), collapse=" ")) ### Extract path and shapefile names tmp <- unlist(strsplit(inputFC, "/"))[-length(unlist(strsplit(inputFC, "/")))] path <- paste(tmp,collapse="/") in.shp.name <- unlist(strsplit(inputFC, "/"))[length(unlist(strsplit(inputFC, "/")))] out.shp.name <- unlist(strsplit(outputFC, "/"))[length(unlist(strsplit(outputFC, "/")))] #### Get variable Names independentVars = strsplit(independentVarString, ";") independentVars = c(unlist(independentVars)) ### Read shapefile using rgdal shp <- readOGR(path, in.shp.name) ### Logistic regression model print("Running model....") lmodel <- LogitRegression(shp@data, y=dependentVar, x=independentVars, penalty=usePenalty) print( lmodel$model ) ### Add columns to data and write shapefile print("Writing Output....") shp@data$Probs <- predict(lmodel$model,shp@data[,rownames(lmodel$model$var)[-1]], type="fitted") shp@data$Residual = lmodel$Residuals[,1] shp@data$StdResid = lmodel$Residuals[,2] writeOGR(shp, path, out.shp.name, driver="ESRI Shapefile", check_exists=TRUE, overwrite_layer=TRUE) ### Write comma seperated ASCII flatfile of model coefficients and diagnositics ### model lrm MODEL OBJECT ### diagTable DATAFRAME OF REGRESSION DIAGNOSTICS ### coefTable DATAFRAME OF REGRESSION COEFFICENTS ### Residuals DATAFRAME OF RESIDUALS AND STANDARDIZED RESIDUALS write.csv(lmodel$coefTable, coefTable) write.csv(lmodel$diagTable, diagTable) #if (AIF == TRUE) { # p <- pentrace(lmodel$model, penalty=seq(0.1,1,by=0.05), which="aic.c") # plot(p) # } print("Model Complete...")
Signed in members can post, follow updates, and more. New here? Register a free account.
Find useful guides, FAQs, and documents to help you navigate and make the most of Esri Community.