loan_data <- read.csv("C:/Users/vj/Desktop/Loan.csv")

library(tidyverse)
## ── Attaching core tidyverse packages ──────────────────────── tidyverse 2.0.0 ──
## ✔ dplyr     1.1.2     ✔ readr     2.1.4
## ✔ forcats   1.0.0     ✔ stringr   1.5.0
## ✔ ggplot2   3.4.3     ✔ tibble    3.2.1
## ✔ lubridate 1.9.2     ✔ tidyr     1.3.0
## ✔ purrr     1.0.2     
## ── Conflicts ────────────────────────────────────────── tidyverse_conflicts() ──
## ✖ dplyr::filter() masks stats::filter()
## ✖ dplyr::lag()    masks stats::lag()
## ℹ Use the conflicted package (<http://conflicted.r-lib.org/>) to force all conflicts to become errors
library(ggthemes)
library(ggrepel)
library(ggplot2)
# View the structure of the dataset
str(loan_data)
## 'data.frame':    5617 obs. of  20 variables:
##  $ ID                  : int  24892 24894 24895 24896 24898 24899 24901 24904 24908 24909 ...
##  $ year                : int  2019 2019 2019 2019 2019 2019 2019 2019 2019 2019 ...
##  $ Gender              : chr  "Male" "Joint" "Joint" "Joint" ...
##  $ approv_in_adv       : chr  "pre" "pre" "pre" "pre" ...
##  $ loan_type           : chr  "type1" "type1" "type1" "type1" ...
##  $ loan_purpose        : chr  "p1" "p1" "p1" "p3" ...
##  $ loan_amount         : int  406500 696500 706500 346500 376500 436500 466500 226500 406500 586500 ...
##  $ rate_of_interest    : num  4.56 4 3.99 4.5 4.88 ...
##  $ Interest_rate_spread: num  0.2 0.304 0.152 1 0.74 ...
##  $ Upfront_charges     : num  595 0 370 5120 1150 ...
##  $ term                : int  360 360 360 360 360 360 360 360 360 360 ...
##  $ Neg_ammortization   : chr  "neg_amm" "not_neg" "not_neg" "not_neg" ...
##  $ interest_only       : chr  "not_int" "not_int" "not_int" "not_int" ...
##  $ property_value      : int  508000 758000 1008000 438000 478000 688000 708000 298000 598000 748000 ...
##  $ total_units         : chr  "1U" "1U" "1U" "1U" ...
##  $ income              : int  9480 10440 10080 5040 5580 6720 9540 7860 5340 12540 ...
##  $ credit_type         : chr  "EXP" "CRIF" "EXP" "EXP" ...
##  $ Credit_Score        : int  834 602 864 860 580 788 501 773 629 688 ...
##  $ age                 : chr  "35-44" "25-34" "35-44" "55-64" ...
##  $ Region              : chr  "south" "North" "North" "North" ...
# View the first few rows of the dataset
head(loan_data)
##      ID year            Gender approv_in_adv loan_type loan_purpose loan_amount
## 1 24892 2019              Male           pre     type1           p1      406500
## 2 24894 2019             Joint           pre     type1           p1      696500
## 3 24895 2019             Joint           pre     type1           p1      706500
## 4 24896 2019             Joint           pre     type1           p3      346500
## 5 24898 2019             Joint         nopre     type1           p3      376500
## 6 24899 2019 Sex Not Available         nopre     type3           p3      436500
##   rate_of_interest Interest_rate_spread Upfront_charges term Neg_ammortization
## 1            4.560               0.2000           595.0  360           neg_amm
## 2            4.000               0.3042             0.0  360           not_neg
## 3            3.990               0.1523           370.0  360           not_neg
## 4            4.500               0.9998          5120.0  360           not_neg
## 5            4.875               0.7395          1150.0  360           not_neg
## 6            3.490              -0.2776          2316.5  360           not_neg
##   interest_only property_value total_units income credit_type Credit_Score
## 1       not_int         508000          1U   9480         EXP          834
## 2       not_int         758000          1U  10440        CRIF          602
## 3       not_int        1008000          1U  10080         EXP          864
## 4       not_int         438000          1U   5040         EXP          860
## 5       not_int         478000          1U   5580         CIB          580
## 6       not_int         688000          1U   6720         CIB          788
##     age  Region
## 1 35-44   south
## 2 25-34   North
## 3 35-44   North
## 4 55-64   North
## 5 55-64 central
## 6 55-64   south
# Summary statistics of the  columns
summary(loan_data)
##        ID             year         Gender          approv_in_adv     
##  Min.   :24892   Min.   :2012   Length:5617        Length:5617       
##  1st Qu.:27049   1st Qu.:2015   Class :character   Class :character  
##  Median :29147   Median :2017   Mode  :character   Mode  :character  
##  Mean   :29148   Mean   :2017                                        
##  3rd Qu.:31248   3rd Qu.:2019                                        
##  Max.   :33386   Max.   :2023                                        
##                                                                      
##   loan_type         loan_purpose        loan_amount      rate_of_interest
##  Length:5617        Length:5617        Min.   :  26500   Min.   :2.375   
##  Class :character   Class :character   1st Qu.: 206500   1st Qu.:3.750   
##  Mode  :character   Mode  :character   Median : 306500   Median :3.990   
##                                        Mean   : 338271   Mean   :4.082   
##                                        3rd Qu.: 446500   3rd Qu.:4.500   
##                                        Max.   :3006500   Max.   :5.875   
##                                                          NA's   :7       
##  Interest_rate_spread Upfront_charges        term       Neg_ammortization 
##  Min.   :-0.8863      Min.   :    0.0   Min.   : 96.0   Length:5617       
##  1st Qu.: 0.1009      1st Qu.:  855.1   1st Qu.:360.0   Class :character  
##  Median : 0.3922      Median : 2817.8   Median :360.0   Mode  :character  
##  Mean   : 0.4630      Mean   : 3394.3   Mean   :335.5                     
##  3rd Qu.: 0.7631      3rd Qu.: 5002.8   3rd Qu.:360.0                     
##  Max.   : 2.5370      Max.   :60000.0   Max.   :360.0                     
##  NA's   :7            NA's   :11                                          
##  interest_only      property_value    total_units            income      
##  Length:5617        Min.   :  38000   Length:5617        Min.   :   660  
##  Class :character   1st Qu.: 288000   Class :character   1st Qu.:  4020  
##  Mode  :character   Median : 438000   Mode  :character   Median :  6000  
##                     Mean   : 513389                      Mean   :  7155  
##                     3rd Qu.: 648000                      3rd Qu.:  8700  
##                     Max.   :6508000                      Max.   :189360  
##                                                                          
##  credit_type         Credit_Score       age               Region         
##  Length:5617        Min.   :500.0   Length:5617        Length:5617       
##  Class :character   1st Qu.:604.0   Class :character   Class :character  
##  Mode  :character   Median :701.0   Mode  :character   Mode  :character  
##                     Mean   :702.1                                        
##                     3rd Qu.:802.0                                        
##                     Max.   :900.0                                        
## 
# Mean of loan_amount
mean(loan_data$loan_amount)
## [1] 338271.4
# Median of loan_amount
median(loan_data$loan_amount)
## [1] 306500
# Standard deviation of loan_amount
sd(loan_data$loan_amount)
## [1] 178185.2
# Minimum and maximum values of loan_amount
min(loan_data$loan_amount)
## [1] 26500
max(loan_data$loan_amount)
## [1] 3006500
# Summary statistics for multiple columns
summary_data <- lapply(loan_data[, c('rate_of_interest', 'Interest_rate_spread', 'Upfront_charges', 'property_value', 'income', 'Credit_Score')],function(x) summary(x[!is.na(x)]))
summary_data
## $rate_of_interest
##    Min. 1st Qu.  Median    Mean 3rd Qu.    Max. 
##   2.375   3.750   3.990   4.082   4.500   5.875 
## 
## $Interest_rate_spread
##    Min. 1st Qu.  Median    Mean 3rd Qu.    Max. 
## -0.8863  0.1009  0.3922  0.4630  0.7631  2.5370 
## 
## $Upfront_charges
##    Min. 1st Qu.  Median    Mean 3rd Qu.    Max. 
##     0.0   855.1  2817.8  3394.3  5002.8 60000.0 
## 
## $property_value
##    Min. 1st Qu.  Median    Mean 3rd Qu.    Max. 
##   38000  288000  438000  513389  648000 6508000 
## 
## $income
##    Min. 1st Qu.  Median    Mean 3rd Qu.    Max. 
##     660    4020    6000    7155    8700  189360 
## 
## $Credit_Score
##    Min. 1st Qu.  Median    Mean 3rd Qu.    Max. 
##   500.0   604.0   701.0   702.1   802.0   900.0
# Getting the shape (rows and columns) of the dataset
shape <- dim(loan_data)
shape  # Display the shape of the dataset
## [1] 5617   20
# Checking for missing values
colSums(is.na(loan_data))
##                   ID                 year               Gender 
##                    0                    0                    0 
##        approv_in_adv            loan_type         loan_purpose 
##                    0                    0                    0 
##          loan_amount     rate_of_interest Interest_rate_spread 
##                    0                    7                    7 
##      Upfront_charges                 term    Neg_ammortization 
##                   11                    0                    0 
##        interest_only       property_value          total_units 
##                    0                    0                    0 
##               income          credit_type         Credit_Score 
##                    0                    0                    0 
##                  age               Region 
##                    0                    0

There are not many rows with missing values, we can continue with original data for our statistical analysis.

##Visual representation of how many loans are pre-approved and Not pre-approved.

# Converting 'approv_in_adv' column to a factor for better visualization
loan_data$approv_in_adv <- factor(loan_data$approv_in_adv)

# Bar plot for 'approv_in_adv' column
library(ggplot2)
ggplot(loan_data, aes(x = approv_in_adv, fill = approv_in_adv)) +
  geom_bar() +
  labs(title = "Approved and Not Approved Count", x = "Approval Status", y = "Count")

There are many Loans which are Not pre-approved ,when compared to approved loans. Now, we compare any Loan amounts distributed between them.

library(ggplot2)

# Boxplot for loan_amount vs. approv_in_adv
ggplot(loan_data, aes(x = approv_in_adv, y = loan_amount, fill = approv_in_adv)) +
  geom_boxplot() +
  labs(title = "Loan Amount Distribution by Approval Status", x = "Approval Status", y = "Loan Amount") +
  theme_minimal()

By the plot, We can’t able to predict the relationship between Loan amount and Approval status. It needs to be assesed by doing statistical analysis further or by doing linear regression model, which we will perform in the further steps.

#Another important variable to predict the Loan amount will be property value of the customer , here we will visualize the relationship between them by using scatter plot.

# Scatterplot for loan_amount vs. property_value
ggplot(loan_data, aes(x = property_value, y = loan_amount)) +
  geom_point() +
  labs(x = "Property Value", y = "Loan Amount") +
  ggtitle("Loan Amount vs. Property Value")

#To get clear visualization , applying log transformation and plot.
# Log-transform 'loan_amount' and 'property_value' for clearer visualization
loan_data$log_loan_amount <- log(loan_data$loan_amount)
loan_data$log_property_value <- log(loan_data$property_value)

# Scatterplot with log-transformed values
ggplot(loan_data, aes(x = log_property_value, y = log_loan_amount)) +
  geom_point() +
  labs(x = "Log Property Value", y = "Log Loan Amount") +
  ggtitle("Log Loan Amount vs. Log Property Value")

Interpretation :By the plot, we can observe a positive relationship between ‘loan_amount’ and ‘property_value’. As property value increases, higher loan amounts might be requested. A positive relationship in a scatterplot suggests that as the ‘property_value’ increases, the ‘loan_amount’ tends to increase as well.

Potential Correlation: The positive slope in the scatterplot indicates a tendency for higher property values to be associated with higher loan amounts.

##Now we didvide property value into couple of group ranges and see if any specific group trends more with having high loan amount approvals.

# Define breaks for property value groups
breaks <- c(0, 1000000, 2000000, 3000000, 4000000, 5000000, 6000000, 7000000)

# Creating a new column 'property_group' based on property value ranges
loan_data$property_group <- cut(loan_data$property_value, breaks = breaks,
                           labels = c('0 - 1M', '1M - 2M', '2M - 3M', '3M - 4M', '4M - 5M', '5M - 6M', '6M - 7M'))

# Calculate mean loan amount for each property group
mean_loan_amounts <- aggregate(loan_data$loan_amount, list(loan_data$property_group), mean)

# Plotting bar plot for mean loan amounts across property value groups
library(ggplot2)
ggplot(mean_loan_amounts, aes(x = Group.1, y = x)) +
  geom_bar(stat = "identity", fill = "skyblue") +
  labs(x = "Property Value Group", y = "Mean Loan Amount", 
       title = "Mean Loan Amount Across Property Value Groups",
       subtitle = "Property Value Ranges for Groups") +
  scale_x_discrete(labels = c('0 - 1M', '1M - 2M', '2M - 3M', '3M - 4M', '4M - 5M', '5M - 6M', '6M - 7M')) +
  theme_minimal()

By the above Bar plot, we can observe for Group 6 ,Loan amount trends more when compared to any other group. Customers having 5000000-6000000 property value able to fetch more loan amounts.

#Relation between another explanatory variable, income of customer vs Loan amount.

# Scatterplot for loan_amount vs. income
ggplot(loan_data, aes(x = income, y = loan_amount)) +
  geom_point() +
  labs(x = "Income", y = "Loan Amount") +
  ggtitle("Loan Amount vs. Income")

library(ggplot2)


# Creating income groups (you can adjust these breaks accordingly)
breaks <- c(0,10000,15000, 20000, 189360)
loan_data$income_group <- cut(loan_data$income, breaks = breaks,
                              labels = c('Low', 'Medium', 'High', 'Very High'))

# Grouping by income and loan approval status, counting occurrences
approval_counts <- with(loan_data, table(income_group, approv_in_adv))

# Converting to data frame for plotting
approval_counts_df <- as.data.frame(approval_counts)

# Renaming columns for clarity
names(approval_counts_df) <- c('Income_Group', 'Approval_Status', 'Count')

# Plotting grouped bar plot
ggplot(approval_counts_df, aes(x = Income_Group, y = Count, fill = Approval_Status)) +
  geom_bar(stat = 'identity', position = 'dodge') +
  labs(x = "Income Group", y = "Count", fill = "Approval Status", 
       title = "Loan Approval Status Across Income Groups") +
  theme_minimal()

Interpretation:There is a positive relationship between ‘loan_amount’ and ‘income’. People with higher incomes might tend to apply for larger loan amounts. However, other factors also influence loan amount ,but we can say higher the income ,the loan amount sanctioned will be more.

#scatter plot for credit score and loan amount

# Scatterplot for loan_amount vs. Credit_Score
ggplot(loan_data, aes(x = Credit_Score, y = loan_amount)) +
  geom_point() +
  labs(x = "Credit Score", y = "Loan Amount") +
  ggtitle("Loan Amount vs. Credit Score")

Noting the absence of a clear trend in the plot between ‘credit_score’ and ‘loan_amount’ . Scatterplot fails to show a discernible pattern or relationship, it implies that no direct or linear association exists between the two variables. This suggests that ‘credit_score’ might not significantly influence or predict ‘loan_amount’ in a straightforward manner.

#Taking categorical variable Loan type ,and plotting a bar plot to see if there is any difference in loan amount distribution based on loan type.

# Bar plot for Loan Amount vs. Loan Type
ggplot(loan_data, aes(x = loan_type, y = loan_amount)) +
  geom_bar(stat = "summary", fun = "mean", fill = "skyblue") +
  labs(x = "Loan Type", y = "Average Loan Amount") +
  ggtitle("Average Loan Amount Across Loan Types")

By observing the above bar plot,The analysis of loan amounts across different loan types reveals distinct trends. Type 1 loans exhibit the highest average loan amount, followed by Type 3 loans, and Type 2 loans show the lowest average loan amount. This observation suggests a clear discrepancy in the loan amounts disbursed among the different loan types. We can say that Loan type will have an impact on deciding Loan amount.

# Creating a box plot to compare loan amounts by gender
ggplot(loan_data, aes(x = Gender, y = loan_amount)) +
  geom_boxplot(fill = "skyblue", alpha = 0.7) +
  labs(x = "Gender", y = "Loan Amount", 
       title = "Comparison of Loan Amounts by Gender") +
  theme_minimal()

# Plotting loan amount by income and gender
ggplot(loan_data, aes(x = income, y = loan_amount, color = Gender)) +
  geom_point(alpha = 0.6) +
  labs(x = "Income", y = "Loan Amount", 
       title = "Loan Amount by Income and Gender") +
  theme_minimal()

By the above plots, we can see Loan amounts distributed for Joint gender is high,when compared to remaining categories.To check the phenomena ,again we plotted scatter plot to visualize the income levels among all genders. From the plot, we can conclude that Joint gender has high income levels , so the Loan amount approval is high.

#Relation between rate of interest and loan amount.

# Scatterplot for loan_amount vs. rate_of_interest
ggplot(loan_data, aes(x = rate_of_interest, y = loan_amount)) +
  geom_point() +
  labs(x = "Rate of Interest", y = "Loan Amount") +
  ggtitle("Loan Amount vs. Rate of Interest")
## Warning: Removed 7 rows containing missing values (`geom_point()`).

By the plot, we can see Rate of interest is associated with Loan amount, and has no impact in predicting loan amount.Different loan amounts are having different interest rates,and absolutely no relation among them that will help us in understanding Loan approval.

##Hypothesis Testing:

To determine the best explanatory variable the explains Loan amount variable , we can perform hypothesis testing using T -test test.consider below scenarios for testing,

Null Hypothesis: The type of approval whether it is pre-approved or not does not have a significant impact on the loan amount. Alternative Hypothesis: The type of approval whether it is pre-approved or not does have a significant impact on the loan amount.

# Separating the data into two groups based on approval type
pre_approved <- loan_data %>% filter(approv_in_adv == "pre")
not_pre_approved <- loan_data %>% filter(approv_in_adv == "nopre")

#  Conducting a Two-Sample t-test
t_test_result <- t.test(pre_approved$loan_amount, not_pre_approved$loan_amount, alternative = "two.sided")

#  Interpret the Results
print(t_test_result)
## 
##  Welch Two Sample t-test
## 
## data:  pre_approved$loan_amount and not_pre_approved$loan_amount
## t = -2.6262, df = 1374.1, p-value = 0.00873
## alternative hypothesis: true difference in means is not equal to 0
## 95 percent confidence interval:
##  -28726.248  -4160.816
## sample estimates:
## mean of x mean of y 
##  324597.3  341040.8

The results indicate that there is a statistically significant difference in mean loan amounts between the ‘pre_approved’ and ‘not_pre_approved’ groups.The p-value of 0.00873 is less than the significance level of 0.05, further supporting the rejection of the null hypothesis.In summary, we have evidence to conclude that the type of approval (pre-approved or not) has a significant impact on the loan amount, with the ‘pre_approved’ group having a lower mean loan amount.

Interpretation:

t-value: The t-value is -2.6262. It measures the difference between the means of the ‘pre-approved’ and ‘not pre-approved’ loan amounts in terms of standard error units. A negative t-value indicates that, on average, ‘not pre-approved’ loans have higher amounts compared to ‘pre-approved’ loans. Degrees of Freedom (df): Indicates the degrees of freedom used in the t-test calculation. Here, it’s approximately 1374.1. p-value: The p-value is 0.00873. It represents the probability of observing a t-value as extreme as the one obtained if there were no true difference in means between ‘pre-approved’ and ‘not pre-approved’ loan amounts. The p-value is below the significance level of 0.05, indicating strong evidence against the null hypothesis. Confidence Interval: The 95% confidence interval for the difference in means (-28726.248 to -4160.816) doesn’t include zero. This suggests a statistically significant difference between the mean loan amounts of ‘pre-approved’ and ‘not pre-approved’ categories. Sample Estimates: The mean loan amount for ‘pre-approved’ loans (mean of x) is estimated to be approximately 324597.3, while for ‘not pre-approved’ loans (mean of y) is estimated to be around 341040.8. Conclusion: The t-test results provide strong evidence of a statistically significant difference between the mean loan amounts of ‘pre-approved’ and ‘not pre-approved’ categories. ‘Not pre-approved’ loans tend to have significantly higher mean loan amounts compared to ‘pre-approved’ loans.

#Performing ANOVA test for Loan amount and Loan type , to determine any relation between loan types to loan amount.

# ANOVA for loan_type
loan_type_anova <- aov(loan_amount ~ loan_type, data = loan_data)
summary(loan_type_anova)
##               Df    Sum Sq   Mean Sq F value Pr(>F)    
## loan_type      2 5.446e+12 2.723e+12   88.43 <2e-16 ***
## Residuals   5614 1.729e+14 3.079e+10                   
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
loan_type_anova <- aov(rate_of_interest
 ~ loan_type, data = loan_data)
summary(loan_type_anova)
##               Df Sum Sq Mean Sq F value   Pr(>F)    
## loan_type      2   15.7   7.826   27.71 1.06e-12 ***
## Residuals   5607 1583.5   0.282                     
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 7 observations deleted due to missingness

Interpretation: Df: Degrees of freedom. For ‘loan_type’, there are 2 degrees of freedom representing the number of categories minus 1. The residual degrees of freedom are 5614. Sum Sq: The sum of squares, indicating the variability attributed to ‘loan_type’ (5.446e+12) and within the groups (1.729e+14). Mean Sq: Mean squares, calculated as the sum of squares divided by the degrees of freedom. F value: The F-statistic, which is 88.43, suggests a high variability between group means compared to within group means. Pr(>F): The p-value associated with the F-statistic is less than 2e-16 (practically 0), indicating strong evidence against the null hypothesis. Conclusion: The ANOVA test for ‘loan_type’ and ‘loan_amount’ indicates a highly significant difference in mean ‘loan_amount’ across different categories within ‘loan_type’. The p-value is extremely small, suggesting that the variability in ‘loan_amount’ is significantly attributed to the different categories of ‘loan_type’. This result implies that ‘loan_type’ has a substantial impact on determining the mean ‘loan_amount’, showing statistical significance.

#Calculate the correlation coefficient of key variables.

# Calculate correlation coefficient between loan_amount and income
correlation_of_propertvalue <- cor(loan_data$loan_amount, loan_data$property_value)
correlation_of_propertvalue
## [1] 0.7175323
# Calculate correlation coefficient between loan_amount and income
correlation_of_income <- cor(loan_data$loan_amount, loan_data$income)
correlation_of_income
## [1] 0.4901126
# Removing NA values from 'loan_amount' and 'rate_of_interest'
Loan_no_na <- na.omit(loan_data[c("loan_amount", "rate_of_interest")])

# Calculating the correlation
correlation_of_interestrate <- cor(Loan_no_na$loan_amount, Loan_no_na$rate_of_interest)
correlation_of_interestrate
## [1] -0.1377864
correlation_of_credit_score <- cor(loan_data$loan_amount, loan_data$Credit_Score)
correlation_of_credit_score
## [1] -0.00409895

Correlation between ‘loan_amount’ and ‘property_value’: 0.7175323

Interpretation: There is a moderate to strong positive linear relationship (0.71) between ‘loan_amount’ and ‘property_value’. As ‘property_value’ increases, ‘loan_amount’ tends to increase as well. Correlation between ‘loan_amount’ and ‘income’: 0.4901126

There exists a moderate positive linear relationship (0.49) between ‘loan_amount’ and ‘income’. This suggests that higher ‘income’ levels tend to relate to higher ‘loan_amounts’. Correlation between ‘loan_amount’ and ‘rate_of_interest’ after handling NA values: -0.1377864

There is a weak negative linear relationship (-0.14) between ‘loan_amount’ and ‘rate_of_interest’. This indicates that as ‘rate_of_interest’ increases, ‘loan_amount’ slightly decreases, but the relationship is not strong. Correlation between ‘loan_amount’ and ‘Credit_Score’: -0.00409895

There is an extremely weak negative linear relationship (-0.004) between ‘loan_amount’ and ‘Credit_Score’. This correlation suggests a negligible or no linear relationship between these variables.

##Doing linear regression model where ‘loan_amount’ is the dependent variable and ‘property_value’ and ‘income’ are the independent variables using the lm() function.

#  Linear Regression model 
lm_model <- lm(loan_amount ~ property_value + income, data = loan_data)
coef(lm_model)
##    (Intercept) property_value         income 
##   1.302058e+05   3.079428e-01   6.984195e+00
summary(lm_model)
## 
## Call:
## lm(formula = loan_amount ~ property_value + income, data = loan_data)
## 
## Residuals:
##      Min       1Q   Median       3Q      Max 
## -1839918   -64793    -7505    64753   903870 
## 
## Coefficients:
##                 Estimate Std. Error t value Pr(>|t|)    
## (Intercept)    1.302e+05  2.946e+03   44.20   <2e-16 ***
## property_value 3.079e-01  4.818e-03   63.91   <2e-16 ***
## income         6.984e+00  2.903e-01   24.06   <2e-16 ***
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## Residual standard error: 118200 on 5614 degrees of freedom
## Multiple R-squared:  0.5602, Adjusted R-squared:   0.56 
## F-statistic:  3576 on 2 and 5614 DF,  p-value: < 2.2e-16

R-squared: The multiple R-squared value (0.5602) indicates that approximately 56.02% of the variance in ‘loan_amount’ is explained by ‘property_value’ and ‘income’ in the model.

Coefficients:

Intercept (Constant Term): The intercept is 1.302e+05. It represents the estimated loan amount when ‘property_value’ and ‘income’ are zero. However, this might not have a practical interpretation.

property_value: The coefficient is 0.308, with a p-value less than 0.001 (highly significant). It suggests that for a one-unit increase in ‘property_value’, the estimated loan amount increases by 0.308 units, holding other variables constant.

income: The coefficient is 6.984, with a p-value less than 0.001 (highly significant). It indicates that for a one-unit increase in ‘income’, the estimated loan amount increases by 6.984 units, holding other variables constant.

Residuals: The residuals show the distribution of errors (differences between predicted and actual values). They follow a range from -1,839,918 to 903,870.

Conclusion: The model suggests that ‘property_value’ and ‘income’ significantly influence ‘loan_amount’. A higher property value or income is associated with a higher estimated loan amount, according to this model. The adjusted R-squared suggests that the model explains a moderate proportion of the variance in loan amounts based on these two predictors. The p-values (< 0.001) for both predictors indicate strong evidence against the null hypothesis, suggesting the coefficients are significantly different from zero.

##Adding all other key attributes to model

#  Multiple Linear Regression in which all key variables are included.
lm_model <- lm(loan_amount ~ property_value + income + Credit_Score + rate_of_interest + loan_type + approv_in_adv , data = loan_data)
summary(lm_model)
## 
## Call:
## lm(formula = loan_amount ~ property_value + income + Credit_Score + 
##     rate_of_interest + loan_type + approv_in_adv, data = loan_data)
## 
## Residuals:
##      Min       1Q   Median       3Q      Max 
## -1840303   -64464    -7070    63712   904622 
## 
## Coefficients:
##                    Estimate Std. Error t value Pr(>|t|)    
## (Intercept)       1.268e+05  1.633e+04   7.763 9.76e-15 ***
## property_value    3.081e-01  4.990e-03  61.754  < 2e-16 ***
## income            7.025e+00  2.905e-01  24.183  < 2e-16 ***
## Credit_Score      2.417e+01  1.372e+01   1.761   0.0782 .  
## rate_of_interest -3.863e+03  3.027e+03  -1.276   0.2020    
## loan_typetype2   -3.091e+03  5.220e+03  -0.592   0.5537    
## loan_typetype3    3.509e+04  7.081e+03   4.955 7.44e-07 ***
## approv_in_advpre  1.990e+03  4.223e+03   0.471   0.6375    
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## Residual standard error: 117900 on 5602 degrees of freedom
##   (7 observations deleted due to missingness)
## Multiple R-squared:  0.5625, Adjusted R-squared:  0.562 
## F-statistic:  1029 on 7 and 5602 DF,  p-value: < 2.2e-16

##Scatter plot to visualize

Mymodel <- lm(loan_amount ~ income, data = loan_data )

rsquared <- summary(Mymodel)$r.squared

loan_data %>%
  ggplot(aes(x = loan_amount, y = income)) +
  geom_point() +
  geom_smooth(method = 'lm', color = 'gray', linetype = 'dashed', se = FALSE) +
  geom_smooth(se = FALSE) +
  labs(title = "Loan Amount vs. Income",
       subtitle = paste("Linear Fit R-Squared =", round(rsquared, 3))) +
  theme_classic()
## `geom_smooth()` using formula = 'y ~ x'
## `geom_smooth()` using method = 'gam' and formula = 'y ~ s(x, bs = "cs")'

A linear relationship between “loan_amount” and “income” means that changes in income have a constant effect on the loan amount, and the relationship can be adequately captured by a linear model, such as simple linear regression.Based on the linear relationship observed in the scatter plot and the absence of heteroscedasticity, we can conclude that further transformations of these variables may not be necessary for modeling the relationship between “loan_amount” and “income.” A linear regression model can be used to understand how changes in income affect loan amounts, and the model’s coefficients will provide insights into the relationship.

Mymodel <- lm(loan_amount ~ property_value, data = loan_data )

rsquared <- summary(Mymodel)$r.squared

loan_data %>%
  ggplot(aes(x = loan_amount, y = property_value)) +
  geom_point() +
  geom_smooth(method = 'lm', color = 'gray', linetype = 'dashed', se = FALSE) +
  geom_smooth(se = FALSE) +
  labs(title = "Loan Amount vs. property value",
       subtitle = paste("Linear Fit R-Squared =", round(rsquared, 3))) +
  theme_classic()
## `geom_smooth()` using formula = 'y ~ x'
## `geom_smooth()` using method = 'gam' and formula = 'y ~ s(x, bs = "cs")'

```