library(readxl)
## Warning: package 'readxl' was built under R version 4.3.2
crimedata <- read_xlsx("C:/Users/micke/Downloads/5062.0newcrime.xlsx", sheet = 1)
set.seed(124)
#first I am setting my testing data to be 125 datapoints while my training have 381
samp1 <- sample((1:506),125)
crime_test <- crimedata[samp1,,]
crime_train <- crimedata[-samp1,]
head(crime_test)
## # A tibble: 6 × 11
##   newcrime agein06 raceaa   sex   ged employed hrsweek  wage restdum chsupdum
##      <dbl>   <dbl>  <dbl> <dbl> <dbl>    <dbl>   <dbl> <dbl>   <dbl>    <dbl>
## 1        0    30.8      0     1     0        1      40  12.5       1        0
## 2        0    38.3      0     0     1        1      43  11         0        0
## 3        1    43.1      1     0     1        1      40   8         1        0
## 4        1    21.7      0     0     0        1      40   9.5       1        0
## 5        0    32.6      0     0     0        1      32   9         1        0
## 6        0    24.6      0     0     0        0       0   0         1        1
## # ℹ 1 more variable: owncar <dbl>
head(crime_train)
## # A tibble: 6 × 11
##   newcrime agein06 raceaa   sex   ged employed hrsweek  wage restdum chsupdum
##      <dbl>   <dbl>  <dbl> <dbl> <dbl>    <dbl>   <dbl> <dbl>   <dbl>    <dbl>
## 1        0    46.4      0     0     0        1       0    20       0        0
## 2        0    44.3      0     1     0        1      55    12       0        1
## 3        0    32.2      0     0     1        0       0     0       1        1
## 4        0    24.2      0     0     0        0       0     0       1        0
## 5        0    28.8      0     0     1        1      40    18       0        0
## 6        0    42.9      0     0     0        1      60    25       0        0
## # ℹ 1 more variable: owncar <dbl>
dim(crime_test)
## [1] 125  11
dim(crime_train)
## [1] 381  11
#for my linear model I am selecting by dependent varaible to be newcrime. For my independent varaibles they are 1.age in 06, 2.raceaa, 3.sex, 4. GED, 5.Employed, 6. hrsweek, 7.Wage, 8. restdum, 9. chestdum, 10.owncar. I tried to choose a wide array of variables that could be causes for new crime. From race, types of crime, education, employment and salary and restitution and owning property like a car. This was to cast a large net of vraibles and see which ones would be effects.
olsmodnc <- lm(newcrime ~ ., data = crime_train)
summary(olsmodnc)
## 
## Call:
## lm(formula = newcrime ~ ., data = crime_train)
## 
## Residuals:
##      Min       1Q   Median       3Q      Max 
## -0.32632 -0.18065 -0.12523 -0.02481  0.98505 
## 
## Coefficients:
##              Estimate Std. Error t value Pr(>|t|)   
## (Intercept) -0.023195   0.086051  -0.270  0.78766   
## agein06      0.003245   0.001830   1.773  0.07704 . 
## raceaa      -0.073222   0.070607  -1.037  0.30040   
## sex         -0.145906   0.048535  -3.006  0.00283 **
## ged          0.024358   0.036777   0.662  0.50817   
## employed    -0.077343   0.100354  -0.771  0.44137   
## hrsweek      0.002752   0.002051   1.342  0.18034   
## wage        -0.001761   0.005041  -0.349  0.72699   
## restdum      0.098271   0.036917   2.662  0.00811 **
## chsupdum     0.010798   0.037233   0.290  0.77196   
## owncar      -0.001743   0.037516  -0.046  0.96297   
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## Residual standard error: 0.3377 on 370 degrees of freedom
## Multiple R-squared:  0.06052,    Adjusted R-squared:  0.03513 
## F-statistic: 2.383 on 10 and 370 DF,  p-value: 0.00954
#intresting details within the linear model is that the R squared is pretty low when it comes to new crime with only a value of .06. Statistically significant values are 1. sex crimes and 2.Restitution pay. Biggest variable that suprised me was hrs.week being a positive correlate to commiting a newcrime I would think that having a full time job would lower your chances of commiting a new crime compared to having only a part time job with a few hours.  
#Next is the Cutoff points. What I want to have are Lower false positives even if it increases false negatives. This is because if this data would ever be used in a courtroom setting as an argument of wether or not the individual is going to jail or not for a new crime I would want the argument to not be used to falsely send someone to jail. So I tried to reduce the amount of false positives by having a relativly high cutoff point for the confusion matrix of .2 but still keep it pretty accurate. 
infit <- predict(olsmodnc)
infit <- ifelse(infit <= .2, 0,1)
table(infit)
## infit
##   0   1 
## 287  94
table(crime_train$newcrime)
## 
##   0   1 
## 329  52
table(crime_train$newcrime,infit)
##    infit
##       0   1
##   0 261  68
##   1  26  26
outfit <- predict(olsmodnc, newdata=crime_test)
outfit <- ifelse(outfit <= .2, 0, 1)
table(crime_test$newcrime,outfit)
##    outfit
##      0  1
##   0 81 21
##   1 18  5
#looking at the results. It seems to show that there is still a lot of false positives at .2 cutoff but at least with a .2 cutoff it can correctly specify individuals that did commit a newcrime. Testing between the different cuoff points with a higher rate like .5 the model will not specify anyone will commit a newcrime. While a .3 it will only specify 1 person would commit a newcrime. Therefore even though there is more false positives then true positives at .2 which I wanted to reduce in the beginning I think this is the best mix of results I want to choose. 
#Also the model infit observations got 287 out of 381 or a goodness of fit of 75 roguhly percent.For the Outfit model of 125 observations it got 86 observations right or roughly a 69 percent goodness of fit. Whith a worse testing data result probably means its not as accurate and probably has a bit of overfitting. 
library(tree)
## Warning: package 'tree' was built under R version 4.3.2
trmod <- tree(newcrime ~ ., data = crime_train)
summary(trmod)
## 
## Regression tree:
## tree(formula = newcrime ~ ., data = crime_train)
## Variables actually used in tree construction:
## [1] "sex"     "restdum" "agein06" "ged"     "wage"   
## Number of terminal nodes:  9 
## Residual mean deviance:  0.1015 = 37.75 / 372 
## Distribution of residuals:
##     Min.  1st Qu.   Median     Mean  3rd Qu.     Max. 
## -0.50000 -0.16200 -0.02222  0.00000 -0.01370  0.98630
plot(trmod)
text(trmod)
title("Return Values for 381 Training Observations")

infit_tr <- predict(trmod)
infit_tr <- ifelse(infit_tr <= .2, 0, 1)
table(crime_train$newcrime,infit_tr)
##    infit_tr
##       0   1
##   0 288  41
##   1  26  26
outfit_tr <- predict(trmod,newdata = crime_test)
outfit_tr <- ifelse(outfit_tr <= .2 , 0, 1)
table(crime_test$newcrime,outfit_tr)
##    outfit_tr
##      0  1
##   0 78 24
##   1 21  2
res<-cbind(crime_test$newcrime,outfit,outfit_tr)
#for the training data the Tree model was amazing with an extreemly high 82 percent goodness of fit but this is in fact a glaring issue. Because with the testing data the tree models goodness of fit was actually only 64 percent(which horrendously low, you can have a better goodness of fit by just guessing everyone will not commit a new crime). Which shows that there is a massive amount of overfitting. To fix this there should be some tree pruning for the tree model. 
colnames(res) <- c("return","ols","tree")
res[1:5,]
##   return ols tree
## 1      0   0    0
## 2      0   0    0
## 3      1   0    1
## 4      1   0    0
## 5      0   0    0
library(corrplot)
## Warning: package 'corrplot' was built under R version 4.3.2
## corrplot 0.92 loaded
Crimemat <- cor(crimedata)
corrplot(Crimemat, method = "ellipse", order="alphabet")
library(BMA)
## Warning: package 'BMA' was built under R version 4.3.2
## Loading required package: survival
## Loading required package: leaps
## Warning: package 'leaps' was built under R version 4.3.2
## Loading required package: robustbase
## Warning: package 'robustbase' was built under R version 4.3.2
## 
## Attaching package: 'robustbase'
## The following object is masked from 'package:survival':
## 
##     heart
## Loading required package: inline
## Warning: package 'inline' was built under R version 4.3.2
## Loading required package: rrcov
## Warning: package 'rrcov' was built under R version 4.3.2
## Scalable Robust Estimators with High Breakdown Point (version 1.7-4)

library(BMA)
y <- crime_train$newcrime
X <- crime_train[, c("agein06", "raceaa", "sex","ged", "employed", "hrsweek", "wage", "restdum", "chsupdum", "owncar")]
crimebma1 <- bicreg(X,y, OR=250)
summary(crimebma1)
## 
## Call:
## bicreg(x = X, y = y, OR = 250)
## 
## 
##   57  models were selected
##  Best  5  models (cumulative posterior probability =  0.6602 ): 
## 
##            p!=0    EV         SD         model 1    model 2    model 3  
## Intercept  100.0   1.213e-01  0.0578211   0.165584   0.118151   0.081081
## agein06     12.1   3.165e-04  0.0010647      .          .          .    
## raceaa       6.8  -4.770e-03  0.0254412      .          .          .    
## sex         84.0  -1.204e-01  0.0681289  -0.151886  -0.124690      .    
## ged          4.2   7.991e-04  0.0085190      .          .          .    
## employed     4.2   3.090e-04  0.0116165      .          .          .    
## hrsweek      6.9   7.099e-05  0.0003897      .          .          .    
## wage         3.9   3.868e-05  0.0006447      .          .          .    
## restdum     50.5   4.590e-02  0.0526549      .       0.082075   0.107694
## chsupdum     3.9   4.783e-04  0.0076312      .          .          .    
## owncar       3.7   1.718e-04  0.0070531      .          .          .    
##                                                                         
## nVar                                        1          2          1     
## r2                                        0.030      0.044      0.025   
## BIC                                      -5.787870  -5.106984  -3.539198
## post prob                                 0.286      0.203      0.093   
##            model 4    model 5  
## Intercept   0.004023   0.088670
## agein06     0.003033   0.002174
## raceaa         .          .    
## sex        -0.149538  -0.172494
## ged            .          .    
## employed       .          .    
## hrsweek        .          .    
## wage           .          .    
## restdum     0.093865      .    
## chsupdum       .          .    
## owncar         .          .    
##                                
## nVar          3          2     
## r2          0.051      0.034   
## BIC        -2.143715  -1.404192
## post prob   0.046      0.032
plot(crimebma1)

imageplot.bma(crimebma1,order="probne0")

y_train <- crime_train$newcrime
X_train <- crime_train[, c("agein06", "raceaa", "sex", "ged", "employed", "hrsweek", "wage", "restdum", "chsupdum", "owncar")]
predictions_train <- predict(crimebma1, newdata = X_train, type = "prob")
posterior_probs1 <- as.numeric(predictions_train$mean)
predictions_test_binary1 <- ifelse(posterior_probs1 <= 0.2, 0, 1)
confusion_matrix_train <- table(Actual = y_train, Predicted = predictions_test_binary1)
print(confusion_matrix_train)
##       Predicted
## Actual   0
##      0 329
##      1  52
y_test <- crime_test$newcrime
X_test <- crime_test[, c("agein06", "raceaa", "sex", "ged", "employed", "hrsweek", "wage", "restdum", "chsupdum", "owncar")]
predictions_test <- predict(crimebma1, newdata = X_test, type = "prob")
posterior_probs <- as.numeric(predictions_test$mean)
predictions_test_binary <- ifelse(posterior_probs <= 0.2, 0, 1)
confusion_matrix_test <- table(Actual = y_test, Predicted = predictions_test_binary)
print(confusion_matrix_test)
##       Predicted
## Actual   0
##      0 102
##      1  23
#After choosing the same .2 cutoff point the Baysian model predicted that for both the training and testing data that there will be no one commiting a new crime. For the goodness of fit for the training data it is 86 percent. For testing data the goodness of fit is 82 percent. Which means that the goodness of fit is the same or higher than both the tree model and OLS model for both the training and testing data. The issue is that this model predicts that no one will commit a newcrime at a .2 cutoff. This can be a good or bad thing depending on your expectations. For example earlier I chose the.2 cutoff because I wanted to reduce the amount of false positives which in this case because there was 0 false positives means that for my argument that this model is by far the best. The only issue is that maybe we do need to have the model predict that some people might go to jail even if more peopole would be falsly accused. Maybe another takeaway from this project is that these predictors are not that strong for claiming someone is going to commit a crime in the future. Which viewed as an ethical dillemma is quite fascinating. we often site that race, class, gender, and types of crimes are often predictors that these individuals will always commit more new crimes in the future. But the data shows that even with a .2 cutoff you cant easily and correctly predict these indvidauls will commit new crimes in the future. It also shows that over 80 percent of individauls once realesed wont commit a newcrime and that society punishing these individuals after being released from prison might be worse then it is good.