R Markdown

This is an R Markdown document. Markdown is a simple formatting syntax for authoring HTML, PDF, and MS Word documents. For more details on using R Markdown see http://rmarkdown.rstudio.com.

When you click the Knit button a document will be generated that includes both content as well as the output of any embedded R code chunks within the document. You can embed an R code chunk like this:

library(ggplot2)
library(dplyr)
## 
## Attaching package: 'dplyr'
## The following objects are masked from 'package:stats':
## 
##     filter, lag
## The following objects are masked from 'package:base':
## 
##     intersect, setdiff, setequal, union
library(viridis)
## Loading required package: viridisLite
library(tsibble)
## 
## Attaching package: 'tsibble'
## The following objects are masked from 'package:base':
## 
##     intersect, setdiff, union
library(tidyverse)
## ── Attaching core tidyverse packages ──────────────────────── tidyverse 2.0.0 ──
## ✔ forcats   1.0.0     ✔ stringr   1.5.0
## ✔ lubridate 1.9.2     ✔ tibble    3.2.1
## ✔ purrr     1.0.2     ✔ tidyr     1.3.0
## ✔ readr     2.1.4
## ── Conflicts ────────────────────────────────────────── tidyverse_conflicts() ──
## ✖ dplyr::filter()       masks stats::filter()
## ✖ lubridate::interval() masks tsibble::interval()
## ✖ dplyr::lag()          masks stats::lag()
## ℹ Use the conflicted package (<http://conflicted.r-lib.org/>) to force all conflicts to become errors
library(forecast)
## Registered S3 method overwritten by 'quantmod':
##   method            from
##   as.zoo.data.frame zoo
library(xts)
## Loading required package: zoo
## 
## Attaching package: 'zoo'
## 
## The following object is masked from 'package:tsibble':
## 
##     index
## 
## The following objects are masked from 'package:base':
## 
##     as.Date, as.Date.numeric
## 
## 
## ######################### Warning from 'xts' package ##########################
## #                                                                             #
## # The dplyr lag() function breaks how base R's lag() function is supposed to  #
## # work, which breaks lag(my_xts). Calls to lag(my_xts) that you type or       #
## # source() into this session won't work correctly.                            #
## #                                                                             #
## # Use stats::lag() to make sure you're not using dplyr::lag(), or you can add #
## # conflictRules('dplyr', exclude = 'lag') to your .Rprofile to stop           #
## # dplyr from breaking base R's lag() function.                                #
## #                                                                             #
## # Code in packages is not affected. It's protected by R's namespace mechanism #
## # Set `options(xts.warn_dplyr_breaks_lag = FALSE)` to suppress this warning.  #
## #                                                                             #
## ###############################################################################
## 
## Attaching package: 'xts'
## 
## The following objects are masked from 'package:dplyr':
## 
##     first, last
library(ggthemes)

##About Data Set

credit_data = read.csv(("/Users/tbs/Downloads/Data Sets 'R'/credit_data.csv"))

# Checking the structure and data types in the dataset
str(credit_data)
## 'data.frame':    279856 obs. of  15 variables:
##  $ Age                     : int  31 25 62 69 52 64 29 30 52 39 ...
##  $ Gender                  : chr  "Male" "Male" "Other" "Female" ...
##  $ Income                  : int  36000 50000 178000 46000 132000 127000 15000 82000 119000 101000 ...
##  $ Credit.Score            : int  604 447 850 668 601 850 378 424 753 575 ...
##  $ Credit.History.Length   : int  487 386 503 349 553 158 89 610 271 424 ...
##  $ Number.of.Existing.Loans: int  5 2 10 6 5 10 1 2 8 5 ...
##  $ Loan.Amount             : int  109373 150000 69099 150000 150000 108702 26819 126550 150000 113257 ...
##  $ Loan.Tenure             : int  221 89 110 148 157 111 108 92 251 12 ...
##  $ Existing.Customer       : chr  "No" "No" "Yes" "Yes" ...
##  $ State                   : chr  "Karnataka" "Karnataka" "Uttar Pradesh" "Karnataka" ...
##  $ City                    : chr  "Mysuru" "Bengaluru" "Kanpur" "Bengaluru" ...
##  $ LTV.Ratio               : num  90.9 91.1 40 87.4 66.2 ...
##  $ Employment.Profile      : chr  "Salaried" "Salaried" "Salaried" "Self-Employed" ...
##  $ Profile.Score           : int  77 43 90 86 90 92 25 58 100 87 ...
##  $ Occupation              : chr  "Doctor" "Software Engineer" "Banker" "Contractor" ...
# Converting Credit_Score column to numeric (if it's not already numeric)
credit_data$Credit.Score <- as.numeric(as.character(credit_data$Credit.Score))

# Verify the conversion has been successful
str(credit_data$Credit.Score)
##  num [1:279856] 604 447 850 668 601 850 378 424 753 575 ...
# Creating a new column for credit score categories:-
credit_data$Credit_Score_type <- cut(credit_data$Credit.Score, 
                                   breaks = c(300, 500, 650, 750, 900),
                                   labels = c("Poor", "Average", "Good", "Excellent"),
                                   include.lowest = TRUE)

# Setting the threshold for credit score
credit_score_threshold <- 450  # Example threshold value

# Create a new column 'Loan_Approval' based on credit score
credit_data$Loan_Approval <- ifelse(credit_data$Credit.Score >= credit_score_threshold, "Approved", "Rejected")

# View the updated dataset
head(credit_data)
##   Age Gender Income Credit.Score Credit.History.Length Number.of.Existing.Loans
## 1  31   Male  36000          604                   487                        5
## 2  25   Male  50000          447                   386                        2
## 3  62  Other 178000          850                   503                       10
## 4  69 Female  46000          668                   349                        6
## 5  52   Male 132000          601                   553                        5
## 6  64 Female 127000          850                   158                       10
##   Loan.Amount Loan.Tenure Existing.Customer         State       City LTV.Ratio
## 1      109373         221                No     Karnataka     Mysuru  90.94343
## 2      150000          89                No     Karnataka  Bengaluru  91.13525
## 3       69099         110               Yes Uttar Pradesh     Kanpur  40.00000
## 4      150000         148               Yes     Karnataka  Bengaluru  87.39337
## 5      150000         157                No     Karnataka     Mysuru  66.15876
## 6      108702         111               Yes    Tamil Nadu Coimbatore  82.33125
##   Employment.Profile Profile.Score        Occupation Credit_Score_type
## 1           Salaried            77            Doctor           Average
## 2           Salaried            43 Software Engineer              Poor
## 3           Salaried            90            Banker         Excellent
## 4      Self-Employed            86        Contractor              Good
## 5           Salaried            90           Teacher           Average
## 6      Self-Employed            92        Contractor         Excellent
##   Loan_Approval
## 1      Approved
## 2      Rejected
## 3      Approved
## 4      Approved
## 5      Approved
## 6      Approved

Creating a Credit_Score_type column that buckets the Credit.Score into 4 categories (Poor, Average, Good, Excellent) using the cut() function. Then, Loan_Approval column that shows “Approved” if the Credit.Score meets or exceeds 450, and “Rejected” otherwise.

data1 = sample_n(credit_data,1000)

taking a random sample of 1,000 rows from the credit_data dataframe and assigning it to a new object called data1

Exploratory Data Analysis (EDA):-

Basic Data Analysis and Visualization

Bar plot for count of population with different credit scores:-

ggplot(credit_data, aes(x = Credit_Score_type, fill = Credit_Score_type)) +
  geom_bar() +
  labs(title = 'Count of population with different credit score',
       x = 'Credit score type',
       y = 'Count') +
  scale_fill_discrete(name = "Credit Score type")

plot shows the distribution of credit scores in India. The x-axis of the graph shows the credit score range, and the y-axis shows the count of people with credit scores in that range.

Box plot for Employment Profile vs. Credit Score

ggplot(credit_data, aes(x = Employment.Profile, y = Credit.Score, fill = Employment.Profile)) +
  geom_boxplot() +
  labs(title = "Employment Profile vs. Credit Score",
       x = "Employment.Profile",
       y = "Credit.Score") +
  scale_fill_discrete(name = "Employment.Profile")

The graph represents the different employment profile like freelancer, salaried, self-employed, student, unemployed with corresponding credit score.

Scatterplot for Credit Score vs. Profile Score:-

ggplot(data1, aes(x = Credit.Score, y = Profile.Score, color = Credit.Score)) +
  geom_point() +
  labs(title = "Credit Score vs. Profile Score",
       x = "Credit Score",
       y = "Profile Score") +
  scale_color_gradient(name = "Credit.Score")

The graph shows a relationship between credit score and profile score. The x-axis represents credit score, and the y-axis represents profile score. The graph shows a positive correlation between the two variables, meaning that as credit score increases, profile score also tends to increase.

# Count the number of loan applicants in each city
city_counts <- table(credit_data$City)

# Convert the city counts to a data frame
city_counts_df <- as.data.frame(city_counts)
names(city_counts_df) <- c('City', 'Applicants')

# Sort the data frame by the number of applicants (descending order)
city_counts_df <- city_counts_df[order(-city_counts_df$Applicants), ]

# Create a color palette for bars
# Example: creating a vector of colors based on the number of cities
colors <- rainbow(length(city_counts_df$City))

# Creating a bar plot for city-wise distribution of loan applicants
ggplot(city_counts_df, aes(x = reorder(City, Applicants), y = Applicants, fill = City)) +
  geom_bar(stat = "identity") +
  scale_fill_manual(values = colors) +  # Set manual colors for bars
  labs(title = "City-wise Distribution of Loan Applicants", x = "City", y = "Number of Applicants") +
  theme(axis.text.x = element_text(angle = 90, vjust = 0.5, hjust=1))

The bar plot represents the city wise distribution of loan applicants. The graph also shows that there is a significant variation in the number of loan applicants from city to city.

# Assuming 'credit_data' is your dataset with 'Credit.Score' and 'Loan.Amount' columns

# Create a scatter plot
ggplot(data1, aes(x = Credit.Score, y = Loan.Amount)) +
  geom_point(color = "orange", alpha = 0.5) +  # Scatter plot with blue color and transparency
  labs(title = "Credit Score vs. Loan Amount", x = "Credit Score", y = "Loan Amount")

The scatter plot represents Credit Score vs. Income, with a fitted linear regression line. The scatter plot shows a positive relationship between Credit Score and Income, meaning that as Income increases, Credit Score also tends to increase. The fitted regression line shows the predicted Credit Score for a given Income level.

# Create a scatter plot with a regression line
ggplot(data1, aes(x = Number.of.Existing.Loans, y = Credit.Score)) +
  geom_point(size = 2, color = "blue") +  # Scatter plot with blue color
  geom_smooth(method = "lm", color = "red") +  # Regression line with red color
  labs(title = "Relationship between Number of Existing Loans and Credit Score",
       x = "Number of Existing Loans", y = "Credit Score")
## `geom_smooth()` using formula = 'y ~ x'

this Indicates a positive relationship.number of existing loans increases, the credit score tends to increase.

# Define bins and labels for Credit Score groups
bins <- c(300, 500, 600, 700, 800, 900)
labels <- c('300-499', '500-599', '600-699', '700-799', '800-900')

# Create Credit Score Group column using cut function
credit_data$Credit_Score_Group <- cut(credit_data$Credit.Score, breaks = bins, labels = labels, right = FALSE)

# Grouping by 'Employment Profile' and 'Credit Score Group' and counting occurrences
grouped_data <- credit_data %>%
  group_by(Employment.Profile, Credit_Score_Group) %>%
  summarise(Count = n()) %>%
  ungroup()
## `summarise()` has grouped output by 'Employment.Profile'. You can override
## using the `.groups` argument.
# Create a grouped bar plot
ggplot(grouped_data, aes(x = Employment.Profile, y = Count, fill = Credit_Score_Group)) +
  geom_bar(stat = "identity", position = "dodge") +
  labs(title = "Number of Individuals in Each Credit Score Group for Every Employment Type",
       x = "Employment Profile", y = "Number of Individuals") +
  scale_fill_brewer(palette = "viridis") +  # Using viridis color palette
  theme_minimal()
## Warning in pal_name(palette, type): Unknown palette viridis

##Correlation Analysis:-

# Subset the relevant columns for correlation analysis
data_subset <- credit_data[, c("Credit.Score", "Income", "Loan.Amount", "Number.of.Existing.Loans", "Credit.History.Length", "LTV.Ratio")]

# Calculate the correlation matrix
correlation_matrix <- cor(data_subset)

# Print the correlation matrix
View(correlation_matrix)

Here’s a breakdown of the interpretation of the correlation matrix:

#1) Credit.Score:- Strong positive correlation (close to 1) with itself (1.000000000). Moderate positive correlations with ‘Income’ (0.220246562) and ‘Loan.Amount’ (0.084304703). Strong positive correlation with ‘Number.of.Existing.Loans’ (0.994557240). Very weak positive correlation with ‘Credit.History.Length’ (0.001920613). Moderate negative correlation with ‘LTV.Ratio’ (-0.378263135).

#2) Income:- Moderate positive correlation with itself (1.000000000). Moderate positive correlations with ‘Credit.Score’ (0.220246562) and ‘Loan.Amount’ (0.387739716). Very weak positive correlation with ‘Number.of.Existing.Loans’ (0.219696262). Very weak negative correlation with ‘LTV.Ratio’ (-0.071813085).

#3) Loan.Amount:- Moderate positive correlation with itself (1.000000000). Very weak positive correlations with ‘Credit.Score’ (0.084304703) and ‘Income’ (0.387739716). Very weak positive correlation with ‘Number.of.Existing.Loans’ (0.084098754). Very weak negative correlation with ‘LTV.Ratio’ (-0.030152167).

#4) Number.of.Existing.Loans: Strong positive correlation with itself (1.000000000). Moderate positive correlations with ‘Credit.Score’ (0.994557240) and ‘Income’ (0.219696262). Very weak positive correlation with ‘Loan.Amount’ (0.084098754). Strong negative correlation with ‘LTV.Ratio’ (-0.379108436).

#5) Credit.History.Length:- Very weak positive correlation with itself (1.000000000). Very weak positive correlations with ‘Credit.Score’ (0.001920613), ‘Income’ (0.002023758), ‘Loan.Amount’ (0.001706414), and ‘Number.of.Existing.Loans’ (0.001956272). Very weak positive correlation with ‘LTV.Ratio’ (0.0006340413).

#6) LTV.Ratio:- Moderate negative correlation with itself (1.000000000). Moderate negative correlations with ‘Credit.Score’ (-0.378263135) and ‘Number.of.Existing.Loans’ (-0.379108436). Very weak negative correlations with ‘Income’ (-0.071813085) and ‘Loan.Amount’ (-0.030152167). Very weak positive correlation with ‘Credit.History.Length’ (0.0006340413). These correlations range from -1 to 1, where:

Values close to 1 indicate a strong positive linear relationship. Values close to -1 indicate a strong negative linear relationship. Values close to 0 indicate a weak or no linear relationship.

Visualize heatmap for correlation matrix

heatmap(correlation_matrix, 
        Colv = NA, Rowv = NA,    # Disable row and column clustering
        col = colorRampPalette(viridis::viridis(10))(100),  # Use viridis color palette
        scale = "none",          # Do not scale data
        margins = c(10, 10),     # Set margins
        main = "Correlation Heatmap"  # Set title
)

As you can see, there is a strong positive correlation between Credit.Score and Number.of.Existing.Loans (0.994). This means that as Credit.Score increases, Number.of.Existing.Loans also tends to increase. There is also a moderate positive correlation between Income and Loan.Amount (0.388). This means that as Income increases, Loan.Amount also tends to increase. There is a weak negative correlation between Credit.Score and LTV.Ratio (-0.378). This means that as Credit.Score increases, LTV.Ratio tends to decrease.

#Hypothesis Testing:-

#Hypothesis 1 (Null Hypothesis for Credit Score by Loan Approval between two groups):-

# Subset data for two groups based on Loan_Approval status (e.g., Approved and Rejected)
group_approved <- credit_data$Credit.Score[credit_data$Loan_Approval == "Approved"]
group_rejected <- credit_data$Credit.Score[credit_data$Loan_Approval == "Rejected"]

# Perform two-sample t-test to compare 'Credit.Score' between the two groups
test_result <- t.test(group_approved, group_rejected)

# View the test result
print(test_result)
## 
##  Welch Two Sample t-test
## 
## data:  group_approved and group_rejected
## t = 886.29, df = 272109, p-value < 2.2e-16
## alternative hypothesis: true difference in means is not equal to 0
## 95 percent confidence interval:
##  283.0962 284.3511
## sample estimates:
## mean of x mean of y 
##  655.5007  371.7771

The t-statistic is 886.29, which is very large and statistically significant. This means that there is very strong evidence to reject the null hypothesis and conclude that there is a difference in means between the two groups. The p-value is less than 2.2e-16, which is very small. This means that the probability of getting a t-statistic as extreme or more extreme than the observed t-statistic, assuming that the null hypothesis is true, is very small. This further supports the conclusion that there is a difference in means between the two groups. The 95% confidence interval for the difference in means is (283.0962, 284.3511). This means that we are 95% confident that the true difference in means between the two groups is between 283.0962 and 284.3511. The mean of group_approved is 655.5007. The mean of group_rejected is 371.7771.

# Define the significance level (alpha)
alpha <- 0.05  # Example significance level

# Check p-value
p_value <- test_result$p.value

# Interpret results based on p-value and significance level
if (p_value < alpha) {
  print("Reject H0. There is no difference in the mean credit scores between the 'Approved' and 'Rejected' groups based on 'Loan_Approval'.")
} else {
  print("Fail to reject H0. There is a difference in the mean credit scores between the 'Approved' and 'Rejected' groups based on 'Loan_Approval'.")
}
## [1] "Reject H0. There is no difference in the mean credit scores between the 'Approved' and 'Rejected' groups based on 'Loan_Approval'."

#Visualization:-

# Subset data for 'Approved' and 'Rejected' groups
group_approved <- credit_data$Credit.Score[credit_data$Loan_Approval == "Approved"]
group_rejected <- credit_data$Credit.Score[credit_data$Loan_Approval == "Rejected"]

# Combine the data for plotting
data_combined <- data.frame(
  Group = c(rep("Approved", length(group_approved)), rep("Rejected", length(group_rejected))),
  Credit.Score = c(group_approved, group_rejected)
)

# Create a boxplot
ggplot(data_combined, aes(x = Group, y = Credit.Score, fill = Group)) +
  geom_boxplot() +
  labs(title = "Comparison of Credit Scores between 'Approved' and 'Rejected' Groups",
       x = "Loan Approval Status", y = "Credit Score") +
  theme_minimal()

The median credit score for approved applicants is 650. This means that half of the approved applicants have credit scores above 650 and half of the approved applicants have credit scores below 650. The median credit score for rejected applicants is 500. This means that half of the rejected applicants have credit scores above 500 and half of the rejected applicants have credit scores below 500. The IQR for approved applicants is 100. This means that the middle 50% of approved applicants have credit scores between 600 and 700. The IQR for rejected applicants is 75. This means that the middle 50% of rejected applicants have credit scores between 525 and 600. The boxplot also shows that there are some approved applicants with credit scores below 500 and some rejected applicants with credit scores above 650. This suggests that credit score is not the only factor that lenders consider when making loan approval decisions. Other factors, such as income, employment history, and debt-to-income ratio, may also be important.

#ANOVA Test:-

# Assuming 'data' contains 'Credit.Score' and 'Employment.Profile' columns
alpha <- 0.05

# Perform ANOVA test
anova_result <- aov(Credit.Score ~ Employment.Profile, data = credit_data)

# Summary of ANOVA results
summary(anova_result)
##                        Df    Sum Sq  Mean Sq F value Pr(>F)    
## Employment.Profile      4 5.665e+07 14162555   536.6 <2e-16 ***
## Residuals          279851 7.386e+09    26392                   
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

The F-value is 536.6, which is very high, and the corresponding p-value is less than 2.2e-16, which is very low. This means that there is very strong evidence to reject the null hypothesis and conclude that there is a statistically significant difference in the means of the two groups on the dependent variable Employment.Profile. In other words, the Employment.Profile factor has a significant effect on the dependent variable.

Linear Model:-

# Assuming 'credit_data' is your dataset with 'Credit.Score' as the dependent variable and 'Income' as the predictor variable

# Fit a simple linear regression model
model <- lm(Credit.Score ~ Income, data = credit_data)

# Summary of the linear regression model
summary(model)
## 
## Call:
## lm(formula = Credit.Score ~ Income, data = credit_data)
## 
## Residuals:
##      Min       1Q   Median       3Q      Max 
## -301.803 -136.584    0.949  139.071  305.999 
## 
## Coefficients:
##              Estimate Std. Error t value Pr(>|t|)    
## (Intercept) 5.189e+02  6.150e-01   843.7   <2e-16 ***
## Income      8.377e-04  7.013e-06   119.4   <2e-16 ***
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## Residual standard error: 159.1 on 279854 degrees of freedom
## Multiple R-squared:  0.04851,    Adjusted R-squared:  0.04851 
## F-statistic: 1.427e+04 on 1 and 279854 DF,  p-value: < 2.2e-16

#Residuals:- The ‘Min’ and ‘Max’ values represent the minimum and maximum values of the residuals (the differences between predicted and observed values).’1Q’, ‘Median’, and ‘3Q’ correspond to the first quartile, median, and third quartile of the residuals, respectively. The residuals are the differences between the observed values of the outcome variable and the values predicted by the model. The small range of the residuals (-301.803 to 305.999) suggests that the model is a good fit for the data.

#Coefficients:- The intercept (Intercept) estimate is 5.189e+02, with a standard error of 6.150e-01 and a highly significant t-value (843.7) and p-value (<2e-16). The coefficient for the ‘Income’ variable is 8.377e-04, with a standard error of 7.013e-06, a t-value of 119.4, and a highly significant p-value (<2e-16). Residual standard error:

The residual standard error (159.1) estimates the standard deviation of the residuals around the regression line.

#R-squared and Adjusted R-squared:- Multiple R-squared (0.04851) represents the proportion of variance in the dependent variable explained by the independent variable (‘Income’ in this case). Adjusted R-squared (0.04851) is the same as R-squared for simple linear regression and indicates the proportion of variance explained adjusted for the number of predictors.

#F-statistic and p-value:- The F-statistic (1.427e+04) assesses the overall significance of the model. It has a very high value with an associated p-value < 2.2e-16, indicating that the overall model is statistically significant.

#Interpretation:- The intercept and ‘Income’ coefficients are both statistically significant (indicated by the low p-values), suggesting that both variables (‘Income’ and intercept) have a significant effect on the dependent variable. The model, as a whole, is statistically significant based on the F-statistic and extremely low p-value. The R-squared value (0.04851) indicates that approximately 4.85% of the variability in the dependent variable is explained by the ‘Income’ variable. In summary, the model shows that ‘Income’ has a statistically significant impact on the dependent variable, but it only explains a small proportion of the variability in the outcome.

# Fit a multiple linear regression model with multiple predictors (e.g., 'Income', 'Credit.History.Length', 'LTV.Ratio')
model <- lm(Credit.Score ~ Income + Credit.History.Length + LTV.Ratio, data = credit_data)

# Summary of the multiple linear regression model
summary(model)
## 
## Call:
## lm(formula = Credit.Score ~ Income + Credit.History.Length + 
##     LTV.Ratio, data = credit_data)
## 
## Residuals:
##     Min      1Q  Median      3Q     Max 
## -374.05 -118.37   14.44  117.79  349.36 
## 
## Coefficients:
##                         Estimate Std. Error  t value Pr(>|t|)    
## (Intercept)            7.784e+02  1.437e+00  541.828   <2e-16 ***
## Income                 7.382e-04  6.525e-06  113.126   <2e-16 ***
## Credit.History.Length  1.638e-03  1.594e-03    1.028    0.304    
## LTV.Ratio             -3.523e+00  1.659e-02 -212.361   <2e-16 ***
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## Residual standard error: 147.6 on 279852 degrees of freedom
## Multiple R-squared:  0.1806, Adjusted R-squared:  0.1806 
## F-statistic: 2.055e+04 on 3 and 279852 DF,  p-value: < 2.2e-16

#Residuals:- Minimum residual: -374.05 First quartile (1Q): -118.37 Median: 14.44 Third quartile (3Q): 117.79 Maximum residual: 349.36

#Coefficients:-

Intercept:- The intercept estimate is 7.784e+02 with a standard error of 1.437e+00. The t-value is 541.828, indicating high significance (<2e-16).

Income:- The coefficient estimate for ‘Income’ is 7.382e-04, with a standard error of 6.525e-06 and a t-value of 113.126. It is highly significant (<2e-16).

Credit.History.Length:- The coefficient estimate is 1.638e-03, with a standard error of 1.594e-03 and a t-value of 1.028. The associated p-value (0.304) suggests it is not statistically significant.

LTV.Ratio:- The coefficient estimate for ‘LTV.Ratio’ is -3.523e+00, with a standard error of 1.659e-02 and a high t-value (-212.361, <2e-16), indicating strong significance.

Residual standard error:- 147.6 on 279852 degrees of freedom. It represents the standard deviation of the residuals around the regression line.

R-squared and Adjusted R-squared:- Multiple R-squared is 0.1806, suggesting that approximately 18.06% of the variance in the dependent variable is explained by the independent variables included in the model. Adjusted R-squared is the same as R-squared for this simple linear regression model.

F-statistic and p-value:- The F-statistic is 2.055e+04 on 3 and 279852 degrees of freedom, with a p-value of < 2.2e-16, indicating that the overall model is statistically significant.

Interpretation:-

‘Income’ and ‘LTV.Ratio’ variables have a statistically significant impact on the dependent variable based on their low p-values (<2e-16). ‘Credit.History.Length’ does not appear to have a significant impact on the dependent variable, considering its higher p-value (0.304). The model, as a whole, is statistically significant based on the F-statistic and extremely low p-value (<2.2e-16). The R-squared value (0.1806) indicates that approximately 18.06% of the variability in the dependent variable is explained by the included independent variables.

# Fit a linear regression model
model <- lm(Credit.Score ~ Income, data = data1)

# Create a scatter plot with the fitted regression line and colors
ggplot(data1, aes(x = Income, y = Credit.Score)) +
  geom_point(color = "red", size = 1) +  # Red-colored scatter plot points
  geom_smooth(method = "lm", se = FALSE, color = "blue") +  # Blue-colored fitted regression line
  labs(title = "Linear Regression: Credit Score vs. Income",
       x = "Income", y = "Credit Score") +
  theme_minimal()
## `geom_smooth()` using formula = 'y ~ x'

scatter plot with a fitted linear regression line showing the relationship between Income (x-axis) and Credit Score (y-axis). Here is an interpretation of the key outputs:

The red colored scatter plot points show the credit score for each individual income amount in the sample data. It allows us to visually inspect if there is a positive, negative or no correlation. The blue regression line represents the best fitted linear model showing the average trend between income and credit score in the data. The position and slope of this blue regression line indicates the strength and direction of the linear relationship between the two variables. In this case, it seems to show a general positive correlation, where higher income amounts have higher credit scores on average. But we can also see variation in the data at each income level, with a range of credit scores among people with similar incomes based on the vertical spread of the red points. So in summary, the key interpretation is that there appears to be a positive linear correlation between income level and credit score on average in this sample data, but there is also variance around the average trend.

# Check for multicollinearity
cor_matrix <- cor(credit_data[, c("Income", "Loan.Amount")])
cor_matrix
##                Income Loan.Amount
## Income      1.0000000   0.3877397
## Loan.Amount 0.3877397   1.0000000
rsquared <- summary(model)$r.squared

ggplot(data = data1, aes(x = Credit.Score, y = Loan.Amount)) +
  geom_point(color = "orange") +
  geom_smooth(method = 'lm', color = 'blue', linetype = 'dashed', se = FALSE) +
  geom_smooth(color = 'red', se = FALSE) +
  labs(
    title = "Loan Amount vs. Credit Score",
    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")'

scatter plot with two fitted lines showing the relationship between Credit Score (x-axis) and Loan Amount (y-axis). Here is an interpretation:

The orange scatter plot points show the approved loan amount for each credit score value for individuals in the sample data. The blue dashed line represents a fitted linear regression model between the two variables. Its position shows the average trend. The red line shows a smoothing through the scatter plot, following the general pattern in the data. The R-squared value measures how closely the linear model fits the data, on a 0 to 1 scale. The value here suggests a moderately good fit. We can observe a general positive correlation - higher credit scores have higher approved loan amounts on average. But there is also variance in loan amount at any particular score.

ggplot(data = data1, aes(x = Credit.Score, y = Income)) +
  geom_point(color = "orange") +
  geom_smooth(method = 'lm', color = 'blue', linetype = 'dashed', se = FALSE) +
  geom_smooth(color = 'red', se = FALSE) +
  labs(
    title = "Income vs. Credit Score",
    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")'

The key interpretation is that there is a positive but relatively weak linear correlation between credit score and income level in this data. The R-squared value quantifies that credit score has lower predictive ability for income level compared to loan amount. And we can see high variability in incomes across the range of credit scores in the scatter plot. Other factors clearly also influence income levels.