-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathemployee_attrition_analysis.Rmd
1858 lines (1558 loc) · 104 KB
/
employee_attrition_analysis.Rmd
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
---
title: "HR data analysis project"
author: "quanggiang169"
date: "2024-10-28"
output:
github_document:
toc: true
toc_depth: 3
toc_float: true
number_sections: true
---
# Employee Retention Analytics: Uncovering the Factors Behind Attrition
<!-- Objective section to explain the aim of the project -->
<div style="margin-top: -10px; font-weight: normal; font-size: 20px;">
Objective: Analyze HR data to understand the factors influencing employee attrition.
</div>
<!-- Horizontal line to separate sections -->
<hr>
## 1. Understanding the context and the problem
### 1.1. Understanding Attrition in the Workplace
**Attrition** refers to the gradual reduction of a company's workforce due to voluntary employee departures, such as resignations, retirements, or other forms of separation where roles are not immediately filled. Unlike turnover, which includes both voluntary and involuntary exits, attrition typically highlights employees' personal decisions to leave, often for new opportunities or lifestyle changes.
Attrition is a natural part of an organization’s lifecycle, but high attrition rates can signal deeper issues and create significant challenges. Managing attrition is crucial for several reasons:
- **Organizational Continuity**: Each departure affects the flow of knowledge, skills, and experience within the company. Frequent attrition disrupts team dynamics, lowers continuity, and may delay projects as new hires get up to speed.
- **Financial Impact**: High attrition incurs substantial costs, including expenses for recruiting, onboarding, and training new employees, which can be as high as 30% to 50% of a departing employee’s annual salary.
- **Employee Morale and Productivity**: High attrition often places extra pressure on remaining staff, who must compensate for the loss. This can lead to employee burnout, reduced morale, and, ultimately, a drop in productivity, affecting team performance and the company’s overall efficiency.
In recent years, attrition rates have reached new highs. For example, according to the U.S. Bureau of Labor Statistics, voluntary departures accounted for 67% of separations in 2021—a significant increase driven by evolving employee priorities, heightened by the pandemic. This trend, known as the “Great Attrition,” underscores the urgent need for companies to understand why employees leave and to implement strategies that foster retention, engagement, and a positive work environment.
**References**
- [The Great Attrition: Facing the labor shortage conundrum - McKinsey & Company](https://www.mckinsey.com/capabilities/people-and-organizational-performance/our-insights/the-organization-blog/the-great-attrition-facing-the-labor-shortage-conundrum)
- [Employee Attrition: Meaning, Impact & Attrition Rate Calculation- AIHR](https://www.aihr.com/blog/employee-attrition/)
- [Attrition: Definition, Types, Causes & Mitigation Tips- SHRM](https://www.shrm.org/in/topics-tools/news/employee-relations/attrition-definition-types-causes-mitigation-tips)
### 1.2. Project Objective
The primary aim of this project is to analyze employee attrition data to uncover the key factors influencing employees' decisions to leave. Through Exploratory Data Analysis (EDA), I hope to identify patterns and insights that reveal which characteristics, such as age, job position, experience, salary, or company culture, most strongly impact employee attrition.
Key questions guiding this analysis include:
- Are certain groups of employees more likely to leave than others?
- What characteristics are commonly found among employees who decide to leave?
- Which factors can be managed or improved to help reduce attrition rates?
By answering these questions, the EDA aims to provide actionable insights that can inform strategies to enhance employee retention and foster a more stable workforce.
## 2. Load libraries
```{r}
library(tidyverse)
library(moments)
library(janitor)
library(knitr)
library(gridExtra)
library(ggcorrplot)
library(reshape2)
library(infotheo)
```
## 3. Checking the data set
### 3.1. Data Dictionary
The IBM HR Analytics Employee Attrition & Performance dataset is a fictional dataset created by IBM data scientists. Since not all features have descriptions, I have made interpretations of what they represent.
You can find the dataset [here](https://www.kaggle.com/pavansubhasht/ibm-hr-analytics-attrition-dataset).
| Feature Name | Data Type | Description |
|--------------------------------|--------------------|------------------------------------------------------------------------------------------------------|
| Age | integer | Employee's age in years |
| Attrition | factor | If the employee stayed or left the company (Yes ; No) |
| BusinessTravel | factor | How often the employee has business travel (Travel_Rarely ; Travel_Frequently ; Non-Travel) |
| DailyRate | integer | Employee's daily rate in USD. |
| Department | factor | Which department the employee belongs to (Sales ; Research & Development ; Human Resources) |
| DistanceFromHome | integer | How far the employee lives from work in kilometers. |
| Education | integer | Employee's education level (1 = Below College ; 2 = College ; 3 = Bachelor ; 4 = Master ; 5 = Doctor)|
| EducationField | factor | Employee's education field (Life Sciences ; Medical ; Marketing ; Technical Degree, Human Resources ; Other)|
| EmployeeCount | integer | How many employees the current record represents. |
| EmployeeNumber | integer | Employee's unique identification number |
| EnvironmentSatisfaction | integer | How satisfied the employee is with the company's environment (1 = Low ; 2 = Medium ; 3 = High ; 4 = Very High) |
| Gender | factor | Employee's gender (Female ; Male) |
| HourlyRate | integer | Employee's hourly rate in USD |
| JobInvolvement | integer | How involved the employee feels with his/her job (1 = Low ; 2 = Medium ; 3 = High ; 4 = Very High) |
| JobLevel | integer | Employee's job level (1 = Junior ; 2 = Mid ; 3 = Senior ; 4 = Manager ; 5 = Director) |
| JobRole | factor | Employee's job role (Sales Executive ; Research Scientist ; Laboratory Technician ; Manufacturing Director ; Healthcare Representative ; Manager ; Sales Representative ; Research Director ; Human Resources) |
| JobSatisfaction | integer | How satisfied the employee feels with his/her job (1 = Low ; 2 = Medium ; 3 = High ; 4 = Very High) |
| MaritalStatus | factor | Employee's marital status (Single ; Married ; Divorced) |
| MonthlyIncome | integer | Employee's monthly income in USD |
| MonthlyRate | integer | Employee's monthly rate in USD |
| NumCompaniesWorked | integer | Number of companies that the employee has already worked. |
| Over18 | factor | If the employee is over 18 years old (Yes) |
| OverTime | factor | If the employee makes overtime (Yes ; No) |
| PercentSalaryHike | integer | The percentage of the amount a salary is increased |
| PerformanceRating | integer | Employee's performance rating (1 = Low ; 2 = Good ; 3 = Excellent ; 4 = Outstanding) |
| RelationshipSatisfaction | integer | How satisfied the employee feels with the relationship with his/her manager (1 = Low ; 2 = Medium ; 3 = High ; 4 = Very High) |
| StandardHours | integer | Employee's standard hours of work per day |
| StockOptionLevel | integer | Employee's stock option level (refer to: What You Should Know About Option Trading Levels) |
| TotalWorkingYears | integer | Total years that the employee has professionally worked |
| TrainingTimesLastYear | integer | Total times that the employee had a training session the last year |
| WorkLifeBalance | integer | How the employee feels about his/her work-life balance (1 = Bad ; 2 = Good ; 3 = Better ; 4 = Best) |
| YearsAtCompany | integer | Total years that the employee has worked at the company |
| YearsInCurrentRole | integer | Total years that the employee has worked in his/her current job role |
| YearsSinceLastPromotion | integer | Total years since the employee had his/her last promotion at the company |
| YearsWithCurrManager | integer | Total years that the employee has worked under his/her current manager |
### 3.2. Loading data set
```{r}
df_hratt <- read_csv("dataset/WA_Fn_UseC_HR_Employee_Attrition.csv", col_types = cols())
```
### 3.3. Renaming columns
```{r}
df_hratt_cln <- clean_names(df_hratt)
```
### 3.4. Checking data dimensions
```{r, echo=FALSE}
# Print the number of rows and columns in the data frame
cat('Number of rows:', nrow(df_hratt_cln), '\n')
cat('Number of cols:', ncol(df_hratt_cln), '\n')
```
### 3.5. Checking data types
```{r, echo=FALSE}
# Display the structure of the dataframe
str(df_hratt_cln)
```
```{r, echo=FALSE}
# Count the number of columns for each data type in the cleaned dataframe
dtype_counts <- table(sapply(df_hratt_cln, class))
print(dtype_counts)
```
### 3.6. Checking missing data
```{r, echo=FALSE}
# Count the number of missing values in each column of the data frame
missing_values <- colSums(is.na(df_hratt_cln))
print(missing_values)
```
Note: Because the data set is fictional, it is free of any NaN values.
### 3.7. Descriptive statistics
#### 3.7.1. Separate Numerical and Categorical Variables
```{r}
# Separate numerical and categorical attributes
num_attributes <- df_hratt_cln %>% select(where(is.numeric))
cat_attributes <- df_hratt_cln %>% select(where(negate(is.numeric)))
```
#### 3.7.2. Create a Summary Data Frame
```{r, echo=FALSE}
# Calculate central tendency: mean, median
mean_values <- colMeans(num_attributes, na.rm = TRUE)
median_values <- apply(num_attributes, 2, median, na.rm = TRUE)
# Calculate distribution: std, min, max, range, skew, kurtosis
std_values <- apply(num_attributes, 2, sd, na.rm = TRUE)
min_values <- apply(num_attributes, 2, min, na.rm = TRUE)
max_values <- apply(num_attributes, 2, max, na.rm = TRUE)
range_values <- max_values - min_values
skewness_values <- apply(num_attributes, 2, function(x) skewness(x, na.rm = TRUE))
kurtosis_values <- apply(num_attributes, 2, function(x) kurtosis(x, na.rm = TRUE))
# Create summary statistics table
summary_stats <- data.frame(
attributes = names(num_attributes),
min = min_values,
max = max_values,
range = range_values,
mean = mean_values,
median = median_values,
std = std_values,
skewness = skewness_values,
kurtosis = kurtosis_values
)
# Display the summary statistics table
kable(summary_stats, format = "simple", row.names = FALSE)
```
#### 3.7.3. Check Unique Value Counts for Categorical Attributes
```{r, echo=FALSE}
# Check how many unique values we have for each categorical attribute
unique_counts <- sapply(cat_attributes, function(x) length(unique(x)))
unique_counts
```
#### 3.7.4. Analyze Target Variable (attrition)
```{r, echo=FALSE}
# Count how many of each class we have in the target variable
attrition_counts <- table(df_hratt_cln$attrition)
attrition_counts
```
### 3.8. Checkpoint
```{r}
# saves the current data set state
write.csv(df_hratt_cln, file = 'dataset/Human_Resources_clean.csv', row.names = FALSE)
```
## 4. Outlining the Hypotheses
### 4.1. Hypothesis generation
| Factor | Hypothesis |
|-----------------------------|-------------------------------------------------------------------------|
| Age | People up to 40s tend to leave. |
| | People 40+ tend not to leave. |
| Education | People that have higher degree of education tend to leave. |
| | People that have lower degree of education tend not to leave. |
| Distance from home | People who live far from work tend to leave. |
| | People who live near work tend not to leave. |
| Marital status | Single people tend to leave. |
| | Married people tend not to leave. |
| Overtime | People who make overtime tend to leave. |
| | People who don't make overtime tend to stay. |
| Performance rating | People who present higher performance ratings tend to leave. |
| | People who present lower performance ratings tend to leave. |
| | People who present medium performance ratings tend not to leave. |
| Job level and role | People who have lower job level tend to leave. |
| | People who have medium and higher job level tend not to leave. |
| | People who weren't promoted for a long time tend to leave. |
| | People who are in the current role for a long time tend to leave. |
| Job involvement | People who feel less involved with the job tend to leave. |
| | People who feel more involved with the job tend not to leave. |
| Job satisfaction | People who feel less satisfied with the job tend to leave. |
| | People who feel more satisfied with the job tend not to leave. |
| Environment satisfaction | People who feel less satisfied with the environment tend to leave. |
| | People who feel more satisfied with the environment tend not to leave. |
| Work life balance | People who have lower work life balance tend to leave. |
| | People who have higher work life balance tend not to leave. |
| Working years | People who have worked professionally for more years tend not to leave. |
| | People who have worked at the same company for more years tend not to leave. |
| | People who are job hoppers tend to leave. |
| Payment | People who are making more money tend not to leave. |
| | People who have lower salary hikes tend to leave. |
| Training | People who didn't receive training for long years tend to leave. |
| | People who constantly received training tend not to leave. |
| Current manager | People who have been working for the same manager for short years tend to leave. |
| | People who have been working for the same manager for long years tend not to leave. |
| | People who have lower quality of relationship with the manager tend to leave. |
| | People who have higher quality of relationship with the manager tend not to leave. |
| Business travel | People who travel more frequently tend to leave. |
| | People who don't travel tend to stay. |
| | People who travel less frequently tend to stay. |
|Other questions that we need to answer| Which departments has more turnover? |
| | Which education field has more turnover? |
### 4.2. Selected Hypotheses
| Category | Hypotheses |
|------------------------------|--------------------------------------------------------------------------------------|
| **Age** | H1. People up to 40s tend to leave. |
| **Education** | H2. People that have higher degree of education tend to leave more. |
| **Distance from home** | H3. People who live far from work tend to leave. |
| **Marital status** | H4. Single people tend to leave. |
| **Overtime** | H5. People who make overtime tend to leave more. |
| **Performance rating** | H6. People who present higher performance ratings tend to leave more. |
| | H7. People who present lower performance ratings tend to leave more. |
| **Job level and role** | H8. People who have lower job level tend to leave more. |
| | H9. People who weren't promoted for a long time tend to leave more. |
| | H10. People who are in the current role for a long time tend to leave more. |
| **Job involvement** | H11. People who feel less involved with the job tend to leave more. |
| **Job satisfaction** | H12. People who feel less satisfied with the job tend to leave more. |
| **Environment satisfaction** | H13. People who feel less satisfied with the environment tend to leave more. |
| **Work life balance** | H14. People who have lower work life balance tend to leave more. |
| **Working years** | H15. People who professionally worked for more years tend to not leave. |
| | H16. People who worked at the same company for more years tend not to leave. |
| | H17. People who are job hoppers tend to leave. |
| **Payment** | H18. People who are making more money tend not to leave. |
| | H19. People who have lower salary hikes tend to leave. |
| **Training** | H20. People who didn't receive training for long years tend to leave more. |
| **Current manager** | H21. People who have been working for the same manager for short years tend to leave more. |
| | H22. People who have lower quality of relationship with the manager tend to leave more. |
| **Business travel** | H23. People who travel more frequently tend to leave more. |
| **Other questions** | H24. Which departments have more turnover? |
| | H25. Which education field has more turnover? |
## 5. Feature Engineering
### 5.1. Loading data set
```{r}
# Loads data set
df_hratt <- read_csv("dataset/Human_Resources_clean.csv")
```
### 5.2. Column filtering
In this step of my analysis, I'm going to remove certain columns from my dataset to simplify the data and focus on the most important information.
1. **Removing `over18` and `standard_hours`:**
- I have a column called `over18`, which indicates whether employees are over 18 years old. Since all employees in my dataset are over 18, this column doesn’t provide any useful information.
- I also have a column called `standard_hours`, which shows the standard working hours for employees. If every employee has the same standard hours, this column also doesn’t help me differentiate between them.
Therefore, I will remove these columns from the dataset to streamline the analysis and retain only the relevant information that can contribute to my insights about employee attrition.
2. **Dropping `employee_count` and `employee_number`:**
- The `employee_count` column shows the total number of employees, but since this number is the same for everyone, it doesn’t provide any unique insights for our analysis.
- The `employee_number` column is like an ID for each employee. While it identifies individuals, it doesn’t give us valuable information about their work or performance.
By removing these columns, I can focus on the information that will help me analyze employee behavior and make better predictions about their actions.
```{r, echo=FALSE}
# Define columns to drop
cols_drop <- c('over18', 'standard_hours', 'employee_count', 'employee_number')
# Drop the columns from df_hratt
df_hratt <- df_hratt[, !(names(df_hratt) %in% cols_drop)]
# View a random sample from the cleaned data
df_hratt[sample(nrow(df_hratt), 1), ]
```
### 5.3. Preparing data for EDA
When I examine my data, I notice that some categories are represented by numbers. For instance, education levels might be coded numerically (e.g., 1 for 'Below College,' 2 for 'College,' etc.). This numerical representation makes the data more challenging to interpret.
To enhance clarity, I will convert these numbers into descriptive labels. By replacing the numerical codes with clear names, my data will become easier to read and understand, ultimately improving the quality of my analysis.
```{r}
# Convert education levels
df_hratt <- df_hratt %>%
mutate(education = recode(education,
`1` = "Below College",
`2` = "College",
`3` = "Bachelor",
`4` = "Master",
`5` = "Doctor"))
# Convert environment satisfaction levels
df_hratt <- df_hratt %>%
mutate(environment_satisfaction = recode(environment_satisfaction,
`1` = "Low",
`2` = "Medium",
`3` = "High",
`4` = "Very High"))
# Convert job involvement levels
df_hratt <- df_hratt %>%
mutate(job_involvement = recode(job_involvement,
`1` = "Low",
`2` = "Medium",
`3` = "High",
`4` = "Very High"))
# Convert job levels
df_hratt <- df_hratt %>%
mutate(job_level = recode(job_level,
`1` = "Junior",
`2` = "Mid",
`3` = "Senior",
`4` = "Manager",
`5` = "Director"))
# Convert job satisfaction levels
df_hratt <- df_hratt %>%
mutate(job_satisfaction = recode(job_satisfaction,
`1` = "Low",
`2` = "Medium",
`3` = "High",
`4` = "Very High"))
# Convert performance rating levels
df_hratt <- df_hratt %>%
mutate(performance_rating = recode(performance_rating,
`1` = "Low",
`2` = "Good",
`3` = "Excellent",
`4` = "Outstanding"))
# Convert relationship satisfaction levels
df_hratt <- df_hratt %>%
mutate(relationship_satisfaction = recode(relationship_satisfaction,
`1` = "Low",
`2` = "Medium",
`3` = "High",
`4` = "Very High"))
# Convert work life balance levels
df_hratt <- df_hratt %>%
mutate(work_life_balance = recode(work_life_balance,
`1` = "Bad",
`2` = "Good",
`3` = "Better",
`4` = "Best"))
```
### 5.4. Checkpoint
```{r}
# Save the current data set state
write.csv(df_hratt, file = "dataset/Human_Resources_fe.csv", row.names = FALSE)
```
## 6. Exploratory data analysis
### 6.1. Loading data set
```{r}
df_hratt <- read.csv("dataset/Human_Resources_fe.csv")
```
### 6.2. Separating data types
```{r}
#selects only numerical attributes
num_attributes <- df_hratt %>% select(where(is.numeric))
#selects only categorical attributes
cat_attributes <- df_hratt %>% select(where(negate(is.numeric)))
```
### 6.3. Univariate Analysis
In this section, I will conduct a univariate analysis to explore the distribution and characteristics of my dataset. I will particularly focus on the target variable, as well as other numerical and categorical variables. This analysis will help me gain insights into the data and better understand the factors influencing employee attrition.
#### 6.3.1. Target Variable
I will start by visualizing the target variable, attrition, using a count plot to compare the number of employees who left the company versus those who stayed. This visualization will help me understand the distribution of attrition within the dataset. After plotting, I observe that a significantly larger number of employees remained in the company compared to those who left.
```{r, echo=FALSE}
# Create a count plot for attrition
ggplot(df_hratt, aes(x = attrition, fill = attrition)) +
geom_bar() +
scale_fill_manual(values = c("Yes" = "#FF9999", "No" = "#99CCFF")) + # Custom colors for bars
labs(title = "Number of Attrition",
x = "Attrition",
y = "Count") +
theme_minimal(base_size = 15) + # Minimal theme with larger base font size
theme(
plot.title = element_text(size = 20, face = "bold", hjust = 0.5), # Center the title
axis.title.x = element_text(size = 16),
axis.title.y = element_text(size = 16),
axis.text = element_text(size = 14), # Larger axis text
legend.position = "none", # Hide legend
panel.grid.major = element_line(color = "lightgray"), # Light grid lines for readability
panel.grid.minor = element_blank(), # No minor grid lines
plot.background = element_rect(fill = "white", color = NA), # White background
plot.margin = margin(1, 1, 1, 1, "cm") # Margin around the plot
) +
coord_cartesian(clip = 'off') # Ensure elements are not clipped
```
To quantify this, I will count how many employees left the company and how many stayed. I will display these numbers along with their percentages. This analysis reveals that most employees (83.88%) stayed, while only a small number (16.12%) left. Understanding these figures helps me gain a clearer perspective on the situation.
```{r, echo=FALSE}
# Separate the data set for easier analysis
df_left <- df_hratt %>% filter(attrition == "Yes")
df_stayed <- df_hratt %>% filter(attrition == "No")
# Count the number of employees who stayed and left
# Calculate totals
total_employees_left <- nrow(df_left)
total_employees_stayed <- nrow(df_stayed)
total_employees <- nrow(df_hratt)
# Print results
cat('Number of employees who left:', total_employees_left, '\n')
cat('This is equivalent to', round((total_employees_left / total_employees) * 100, 2), '% of the total employees.\n\n')
cat('Number of employees who stayed:', total_employees_stayed, '\n')
cat('This is equivalent to', round((total_employees_stayed / total_employees) * 100, 2), '% of the total employees.\n')
```
#### 6.3.2. Numerical Variables
Next, I will visualize the distribution of all numerical attributes in the dataset using histograms. This step allows me to examine the frequency distribution of numerical variables, helping to identify patterns such as skewness, central tendencies, and potential outliers.
```{r histogram-plotting-num, echo=FALSE, fig.width=10, fig.height=8}
# Set up to show two plots per row
par(mfrow = c(2, 2), mar = c(5, 5, 4, 2) + 0.1, oma = c(2, 2, 2, 2))
# Loop through each numerical attribute to create a clear histogram
for (col in names(num_attributes)) {
hist(num_attributes[[col]],
main = paste("Histogram of", col),
xlab = col,
col = "lightblue",
breaks = 30,
cex.main = 1.5, # Title size for readability
cex.lab = 1.3, # Label size
cex.axis = 1.2, # Axis size
border = "darkblue",
las = 1) # Make axis labels horizontal for clarity
}
# Reset layout after plotting
par(mfrow = c(1, 1))
```
As we can see, except for the age variable, no other variable follows a normal distribution, and even age is not perfectly normal. Therefore, it's better to leave the age variable as it is, rather than attempting normalization, which could lead to errors.
#### 6.3.3. Categorical Variables
Finally, I will analyze the categorical variables through count plots for each attribute. I will create subplots for each categorical variable, enabling me to compare the counts across different categories effectively. This step enhances my understanding of how various categorical factors are distributed in the dataset.
```{r histogram-plotting-cat, echo=FALSE, fig.width=14, fig.height=12}
# Define a custom pastel color palette
pastel_colors <- c("#FFB3BA", "#FFDFBA", "#FFFFBA", "#BAFFBA", "#BAE1FF", "#FFBAF3", "#FFABAB")
# Loop through each categorical column to create horizontal count plots
# Setting up a layout of 3x3 for every 9 plots
num_plots <- ncol(cat_attributes)
plots_per_page <- 9
for (i in seq_along(cat_attributes)) {
# Check if a new page is needed and set up layout
if ((i - 1) %% plots_per_page == 0) {
par(mfrow = c(3, 3), mar = c(5, 10, 4, 2) + 0.1, oma = c(2, 2, 2, 2)) # Increased left margin
}
# Create a table of counts for the category
counts <- table(cat_attributes[[i]])
colors <- pastel_colors[1:length(counts)]
# Create a horizontal bar plot with narrow bars and clear labels
barplot(counts,
main = paste("Count for", names(cat_attributes)[i]),
xlab = names(cat_attributes)[i],
col = colors,
border = "darkblue",
cex.main = 1.2, # Title size for readability
cex.lab = 1.1, # Label size
cex.axis = 1.1, # Axis size
cex.names = 1.1, # Label size on bars
horiz = TRUE, # Horizontal bar plot
las = 1, # Horizontal axis labels
space = 1.5, # Increased spacing between bars
width = 0.6) # Narrower bar width for better spacing
}
# Reset layout after plotting
par(mfrow = c(1, 1))
```
### 6.4 Bivariate analysis - hypotheses validation
#### H1. People up to 40s tend to leave. **<span style="color: green;">TRUE</span>**
```{r, echo=FALSE}
# Convert 'attrition' to a factor to use it as a hue
df_hratt <- df_hratt %>%
mutate(attrition = as.factor(attrition))
# Logistic regression to examine the association between attrition and age
logistic_model_1 <- glm(attrition ~ age, data = df_hratt, family = binomial)
print(logistic_model_1)
```
```{r, echo=FALSE}
# Extract p-value from the model to assess significance
p_value <- summary(logistic_model_1)$coefficients[2, 4] # P-value for the 'age' variable
# Check p-value and draw conclusions
if (p_value < 0.05) {
result <- "There is a significant association between attrition and age."
} else {
result <- "There is no significant association between attrition and age."
}
# Print conclusion
print(result)
```
```{r, echo=FALSE, fig.width=12, fig.height=6}
# Create the first plot: Attrition rate per age
plot1 <- ggplot(data = df_hratt, aes(x = age, fill = attrition)) +
geom_bar(position = "fill", color = "black") + # Adding outline for better clarity
scale_fill_manual(values = c("lightgray", "blue")) + # Set colors for attrition
ggtitle("Attrition Rate per Age") +
theme_minimal() +
theme(
plot.title = element_text(size = 20, face = "bold"),
legend.title = element_text(size = 15),
legend.text = element_text(size = 15),
axis.text.x = element_text(angle = 45, hjust = 1) # Rotate x-axis labels for better readability
) +
labs(fill = "Attrition") # Set legend title
# Create age groups with specified order
df_hratt <- df_hratt %>%
mutate(age_group = factor(case_when(
age < 30 ~ "Under 30",
age < 40 ~ "30-39",
age < 50 ~ "40-49",
TRUE ~ "50 and above"
), levels = c("Under 30", "30-39", "40-49", "50 and above"))) # Specify order
# Create the second plot: Proportion of Attrition by Age Group
plot2 <- ggplot(data = df_hratt, aes(x = age_group, fill = attrition)) +
geom_bar(position = "fill", color = "black") + # Adding outline for better clarity
scale_fill_manual(values = c("lightgray", "blue")) + # Set colors for attrition
ggtitle("Proportion of Attrition by Age Group") +
theme_minimal() +
theme(
plot.title = element_text(size = 20, face = "bold"),
legend.title = element_text(size = 15),
legend.text = element_text(size = 15)
) +
labs(fill = "Attrition") + # Set legend title
ylab("Proportion") + # Add label for y-axis
scale_y_continuous(labels = scales::percent) # Convert y-axis labels to percentages
# Display the plots side by side
grid.arrange(plot1, plot2, ncol = 2)
```
This analysis looks at how age affects whether people leave or stay (attrition). The two variables used are *attrition* (Yes or No) and *age* (ranging from 18 to 60 years old). A logistic regression test was done to see if age is related to attrition. The result showed a p-value less than 0.05, which means that there is a significant association between age and attrition. Additionally, two bar charts were created to show how attrition is distributed across different age groups. The charts show that people under 40 have a higher rate of leaving (attrition) compared to those over 40.
**Conclusion:**
The analysis supports the hypothesis H1, showing a clear association between age and attrition.
#### H2. People that have higher degree of education tend to leave more. **<span style="color: red;">FALSE</span>**
```{r, echo=FALSE}
# Create a contingency table
table_e <- table(df_hratt$attrition, df_hratt$education)
# Perform Chi-squared test
chi_squared_test_2 <- chisq.test(table_e)
print(chi_squared_test_2)
```
```{r,echo=FALSE}
if (chi_squared_test_2$p.value < 0.05) {
print("There is a significant association between attrition and education.")
} else {
print("There is no significant association between attrition and education.")
}
```
```{r, echo=FALSE, fig.width=12, fig.height=6}
# Create the rate plot using ggplot2 with softer colors
ggplot(data = df_hratt, aes(x = education, fill = attrition)) +
geom_bar(position = "fill", color = "black") + # Adding outline for better clarity
scale_fill_manual(values = c("lightgray", "blue")) + # Softer shades for colors
labs(
title = "Attrition Rate per Education Field",
x = "Education Level \n(1 = Below College ; 2 = College ; 3 = Bachelor ; 4 = Master ; 5 = Doctor)",
fill = "Attrition"
) +
theme_minimal() +
theme(
plot.title = element_text(size = 20, face = "bold"),
axis.title.x = element_text(size = 16),
legend.title = element_text(size = 15),
legend.text = element_text(size = 15)
)
```
This analysis explores the association between education level and attrition. The two variables examined are *attrition* (Yes or No) and *education* (ranging from Below College to Doctorate). A Chi-square test was performed to determine if there is an association between education level and attrition. The result yielded a p-value greater than 0.05, which suggests that there is no significant association between education and attrition. Additionally, a bar chart was created to visualize the attrition rate across different education levels (Below College, College, Bachelor, Master, Doctor). The chart shows that the attrition rate is approximately 0.125 across all education levels.
**Conclusion:**
The analysis does not support the hypothesis H2.
#### H3. People who live far from work tend to leave. (Need for further analysis)
```{r, echo=FALSE}
# Logistic regression to examine the association between attrition and distance_from_home
logistic_model_3 <- glm(attrition ~ distance_from_home, data = df_hratt, family = binomial)
print(logistic_model_3)
```
```{r, echo=FALSE}
# Extract p-value from the model to assess significance
p_value <- summary(logistic_model_3)$coefficients[2, 4] # P-value for the 'distance_from_home' variable
# Check p-value and draw conclusions
if (p_value < 0.05) {
result <- "There is a significant association between attrition and distance from home."
} else {
result <- "There is no significant association between attrition and distance from home."
}
# Print conclusion
print(result)
```
```{r, echo=FALSE, fig.width=12, fig.height=6}
# Create the bar plot
ggplot(df_hratt, aes(x = distance_from_home, fill = attrition)) +
geom_bar(position = "fill", color = "black", alpha = 0.7) +
labs(
title = "Attrition Probabilities per Distance from Home",
x = "Distance from Home",
y = "Count",
fill = "Attrition"
) +
scale_fill_manual(values = c("lightgray", "blue")) +
theme_minimal() +
theme(
plot.title = element_text(size = 20, face = "bold"),
axis.title.x = element_text(size = 16),
axis.title.y = element_text(size = 16),
legend.title = element_text(size = 15),
legend.text = element_text(size = 15)
)
```
The bar chart displays the distribution of attrition (Yes/No) across different distances from home. From the chart, it can be observed that there is no clear trend indicating an increase in attrition as the distance from home increases. The proportions of employees leaving (shown in blue) do not exhibit a significant rise across the different distance categories.
**Conclusion:**
Based on the Logistic Regression analysis (p-value < 0.05), there is a significant association between attrition and distance from home, suggesting that employees living farther from work are more likely to leave. However, the bar chart does not visually support a clear increase in attrition with distance, highlighting the need for further analysis to better understand this relationship.
#### H4. Single people tend to leave more. **<span style="color: green;">TRUE</span>**
```{r, echo=FALSE}
# Create a contingency table
table_ms <- table(df_hratt$attrition, df_hratt$marital_status)
# Perform Chi-squared test
chi_squared_test_4 <- chisq.test(table_ms)
print(chi_squared_test_4)
```
```{r,echo=FALSE}
if (chi_squared_test_4$p.value < 0.05) {
print("There is a significant association between attrition and marital status.")
} else {
print("There is no significant association between attrition and marital status.")
}
```
```{r, echo=FALSE, fig.width=12, fig.height=6}
# Ensure 'attrition' and 'marital_status' columns are factors
df_hratt <- df_hratt %>%
mutate(attrition = as.factor(attrition),
marital_status = factor(marital_status, levels = names(sort(table(marital_status), decreasing = TRUE))))
# Create the rate plot with custom colors and ordered marital status
ggplot(data = df_hratt, aes(x = marital_status, fill = attrition)) +
geom_bar(position = "fill") +
scale_fill_manual(values = c("lightgray", "blue")) + # Set custom color palette
labs(
title = "Attrition Probabilities per Marital Status",
x = "Marital Status",
fill = "Attrition"
) +
theme_minimal() +
theme(
plot.title = element_text(size = 20, face = "bold"),
axis.title.x = element_text(size = 16),
legend.title = element_text(size = 15),
legend.text = element_text(size = 15)
)
```
This analysis explores the association between marital status and attrition. The two variables examined are attrition (Yes or No) and marital status (Single, Married, Divorced). A Chi-square test was performed to determine if there is an association between marital status and attrition. The result yielded a p-value less than 0.05, which suggests that there is a significant association between marital status and attrition. Additionally, a bar chart was created to visualize the attrition rate across different marital statuses (Single, Married, Divorced). The chart shows that the attrition rate for single employees is higher compared to those who are married or divorced.
**Conclusion:**
The analysis supports the hypothesis H4.
#### H5. People who make overtime tend to leave more. **<span style="color: green;">TRUE</span>**
```{r, echo=FALSE}
# Create a contingency table
table_ot <- table(df_hratt$attrition, df_hratt$over_time)
# Perform Chi-squared test
chi_squared_test_5 <- chisq.test(table_ot)
print(chi_squared_test_5)
```
```{r,echo=FALSE}
if (chi_squared_test_5$p.value < 0.05) {
print("There is a significant association between attrition and overtime.")
} else {
print("There is no significant association between attrition and overtime.")
}
```
```{r, echo=FALSE, fig.width= 12, fig.height= 6}
# Create the rate plot with custom colors and ordered overtime
ggplot(df_hratt, aes(x = over_time, fill = attrition)) +
geom_bar(position = "fill", color ="black") +
scale_fill_manual(values = c("lightgray", "blue")) +
labs(
title = "Attrition Probabilities per overtime",
x = "Overtime",
fill = "Attrition"
) +
scale_x_discrete(labels = c("No" = "No overtime", "Yes" = "With overtime")) + # Custom x-tick labels
theme_minimal() +
theme(
plot.title = element_text(size = 20, face = "bold"),
axis.title.x = element_text(size = 16),
legend.title = element_text(size = 15),
legend.text = element_text(size = 15)
)
```
This analysis explores the association between overtime and attrition. The two variables examined are overtime (Yes or No) and attrition (Yes or No). A Chi-square test was performed to determine if there is an association between overtime and attrition. The result indicated a significant association between the two variables. Additionally, a bar chart was created to visualize the attrition rate for employees who make overtime compared to those who do not. The chart shows that employees who make overtime have a higher attrition rate compared to those who do not.
**Conclusion:**
The analysis supports the hypothesis H5
#### H6. People who present higher performance ratings tend to leave more. **<span style="color: red;">FALSE</span>**
#### H7. People who present lower performance ratings tend to leave more. **<span style="color: red;">FALSE</span>**
```{r, echo=FALSE}
# Create a contingency table
table_pr <- table(df_hratt$attrition, df_hratt$performance_rating)
# Perform Chi-squared test
chi_squared_test_6 <- chisq.test(table_pr)
print(chi_squared_test_6)
```
```{r,echo=FALSE}
if (chi_squared_test_6$p.value < 0.05) {
print("There is a significant association between attrition and performance ratings.")
} else {
print("There is no significant association between attrition and performance ratings.")
}
```
```{r, echo=FALSE, fig.width= 12, fig.height= 6}
# Create the rate plot for attrition based on performance rating
ggplot(df_hratt, aes(x = performance_rating, fill = attrition)) +
geom_bar(position = "fill") +
scale_fill_manual(values = c("lightgray", "blue")) +
labs(title = "Attrition Probabilities per performance rating",
x = "Performance rating",
fill = "Attrition") +
theme_minimal(base_size = 15) +
theme(plot.title = element_text(size = 20),
axis.title.x = element_text(size = 16),
legend.title = element_text(size = 15),
legend.text = element_text(size = 15))
```
This analysis examines the association between performance ratings and attrition, specifically testing whether employees with either higher or lower performance ratings have different rates of attrition. The two variables analyzed are performance rating (categorized as Outstanding and Excellent) and attrition (Yes or No). A Chi-square test was conducted to check for any association between performance ratings and attrition, and the results yielded a p-value greater than 0.05, indicating no statistically significant association. A bar chart was generated to visualize attrition rates across different performance ratings, showing similar attrition rates for both Outstanding and Excellent ratings, with no data available for Low and Good ratings.
**Conclusion:**
The analysis does not support either hypothesis H6 or H7. There is no significant association between performance rating and attrition, as employees with both higher and lower ratings exhibit similar rates of attrition.
#### H8. People who have lower job level tend to leave more. **<span style="color: green;">TRUE</span>**
```{r, echo=FALSE}
# Create a contingency table
table_jl <- table(df_hratt$attrition, df_hratt$job_level)
# Perform Chi-squared test
chi_squared_test_8 <- chisq.test(table_jl)
print(chi_squared_test_8)
```
```{r,echo=FALSE}
if (chi_squared_test_8$p.value < 0.05) {
print("There is a significant association between attrition and job level.")
} else {
print("There is no significant association between attrition and job level.")
}
```
```{r, echo=FALSE, fig.width= 12, fig.height= 6}
ggplot(df_hratt, aes(x = job_level, fill = attrition)) +
geom_bar(position = "fill") +
scale_fill_manual(values = c("lightgray", "blue")) + # Adjust colors for attrition categories
labs(title = "Attrition Probabilities per job level",
x = "Job level \n(1 = Junior ; 2 = Mid ; 3 = Senior ; 4 = Manager; 5 = Director)",
fill = "Attrition") +
theme_minimal(base_size = 15) +
theme(plot.title = element_text(size = 20),
axis.title.x = element_text(size = 16),
legend.title = element_text(size = 15),
legend.text = element_text(size = 15))
```
This analysis examines the association between job level and attrition, specifically testing whether employees at lower job levels tend to have higher rates of attrition. The two variables analyzed are job level (categorized as Junior, Mid, Senior, Manager, and Director) and attrition (Yes or No). A Chi-square test was conducted to determine if there is an association between job level and attrition, with results yielding a p-value less than 0.05, indicating a statistically significant association between these two variables. A bar chart was also created to show attrition rates across job levels. The chart indicates that Junior employees have the highest attrition rate, followed by Senior, Mid, Manager, and Director.
It’s noteworthy that although Mid-level employees show a lower attrition rate than Senior-level employees, the overall trend still aligns with the hypothesis. The general pattern observed is that employees in lower-level positions, particularly those at the Junior level, exhibit higher rates of attrition compared to those at higher levels.
**Conclusion:**
The analysis supports hypothesis H8.
#### H9. People who weren't promoted for long time tend to leave more. **<span style="color: red;">FALSE</span>**
```{r, echo=FALSE}
# Logistic regression to examine the association between attrition and years_since_last_promotion
logistic_model_10 <- glm(attrition ~ years_since_last_promotion, data = df_hratt, family = binomial)
print(logistic_model_10)
```
```{r,echo=FALSE}
# Extract p-value from the model to assess significance
p_value <- summary(logistic_model_10)$coefficients[2, 4] # P-value for the 'years_since_last_promotion' variable
# Check p-value and draw conclusions
if (p_value < 0.05) {
result <- "There is a significant association between attrition and years since last promotion."
} else {
result <- "There is no significant association between attrition and years since last promotion."
}
# Print conclusion
print(result)
```
```{r, echo=FALSE, fig.width= 12, fig.height= 6}
ggplot(df_hratt, aes(x = years_since_last_promotion, fill = attrition)) +
geom_bar(position = "fill") +
scale_fill_manual(values = c("lightgray", "blue")) + # Adjust colors for attrition categories
labs(title = "Attrition Probabilities per Years since last promotion",
x = "years_since_last_promotion",
fill = "Attrition") +
theme_minimal(base_size = 15) +
theme(plot.title = element_text(size = 20),
axis.title.x = element_text(size = 16),
legend.title = element_text(size = 15),
legend.text = element_text(size = 15))
```
This analysis examines the association between the length of time since an employee’s last promotion and their likelihood of attrition, testing whether employees who have not been promoted for a longer period are more likely to leave. The two variables analyzed are years_since_last_promotion and attrition (Yes or No). A Logistic regression test was conducted to assess if there is an association between these variables, yielding a p-value greater than 0.05, suggesting no statistically significant association between years since last promotion and attrition. Additionally, a bar chart was created to visualize attrition rates across different intervals of years since last promotion. The chart indicates no clear pattern linking the time since last promotion to attrition rates.
**Conclusion:**
The analysis does not support hypothesis H9.
#### H10. People who are in the current role for long time tend to leave more. (Need for further analysis)
```{r, echo=FALSE}
# Logistic regression to examine the association between attrition and years in current role
logistic_model_10 <- glm(attrition ~ years_in_current_role, data = df_hratt, family = binomial)
print(logistic_model_10)
```
```{r,echo=FALSE}
# Extract p-value from the model to assess significance
p_value <- summary(logistic_model_10)$coefficients[2, 4] # P-value for the 'years_in_current_role' variable
# Check p-value and draw conclusions
if (p_value < 0.05) {
result <- "There is a significant association between attrition and years in current role."
} else {
result <- "There is no significant association between attrition and years in current role."
}
# Print conclusion
print(result)
```
```{r, echo=FALSE, fig.width= 12, fig.height= 6}
ggplot(df_hratt, aes(x = years_in_current_role, fill = attrition)) +
geom_bar(position = "fill", alpha = 0.7, color = "black") +
labs(title = "Attrition Probabilities per years in current role",
x = "Years in current role",
fill = "Attrition") +
scale_fill_manual(values = c("lightgray", "blue")) +
theme_minimal(base_size = 15) +
theme(plot.title = element_text(size = 20),
axis.title.x = element_text(size = 16),
legend.title = element_text(size = 15),
legend.text = element_text(size = 15))
```
This analysis examines whether employees who have remained in their current role for a longer duration are more likely to leave, testing the hypothesis that a prolonged time in the current role increases attrition likelihood. The two variables analyzed are years_in_current_role and attrition (Yes or No). A Logistic regression test was conducted, yielding a p-value less than 0.05, indicating a statistically significant association between years in the current role and attrition. However, a bar chart visualizing attrition rates across various lengths of time in the current role does not display a clear pattern or trend supporting this association.
**Conclusion:**
The Logistic regression analysis suggests a statistically significant association between years in the current role and attrition. However, this finding is not supported by the bar chart, which shows no distinct relationship between length of time in the current role and attrition rates. This discrepancy indicates that while a statistically significant association exists, it is not consistently observed across all visualized data points.
#### H11. People who feel less involved with the job tend to leave more. **<span style="color: green;">TRUE</span>**
```{r, echo=FALSE}
# Create a contingency table
table_ji <- table(df_hratt$attrition, df_hratt$job_involvement)
# Perform Chi-squared test
chi_squared_test_11 <- chisq.test(table_ji)
print(chi_squared_test_11)
```
```{r,echo=FALSE}
if (chi_squared_test_11$p.value < 0.05) {
print("There is a significant association between attrition and job involvement.")
} else {
print("There is no significant association between attrition and job involvement.")
}
```
```{r, echo=FALSE, fig.width= 12, fig.height= 6}
ggplot(df_hratt, aes(x = factor(job_involvement), fill = attrition)) +
geom_bar(position = "fill") +
scale_fill_manual(values = c("lightgray", "blue")) + # Specify colors for attrition categories
labs(title = "Attrition Probabilities per job involvement level",
x = "Job involvement level",
fill = "Attrition") +
theme_minimal(base_size = 15) +
theme(plot.title = element_text(size = 20),
axis.title.x = element_text(size = 16),
legend.title = element_text(size = 15),
legend.text = element_text(size = 15))
```
This analysis explores the association between job involvement and attrition, testing the hypothesis that people with lower job involvement are more likely to leave. The two variables analyzed are attrition (Yes or No) and job_involvement (categorized as Low, Medium, High, Very High). A Chi-square test was conducted, showing a significant association between job involvement and attrition. The bar chart visualizing attrition rates across the different levels of job involvement indicates that the highest attrition rate is observed in the Low job involvement category, followed by Medium, High, and Very High involvement categories in descending order. This pattern suggests that lower job involvement may be associated with higher attrition rates.
**Conclusion:** The analysis supports hypothesis H11.
#### H12. People who feel less satisfied with the job tend to leave more. **<span style="color: green;">TRUE</span>**
```{r, echo=FALSE}
# Create a contingency table
table_js <- table(df_hratt$attrition, df_hratt$job_satisfaction)
# Perform Chi-squared test
chi_squared_test_12 <- chisq.test(table_js)
print(chi_squared_test_12)
```
```{r,echo=FALSE}
if (chi_squared_test_12$p.value < 0.05) {
print("There is a significant association between attrition and job satisfaction.")
} else {
print("There is no significant association between attrition and job satisfaction.")
}
```
```{r, echo=FALSE, fig.width= 12, fig.height= 6}
ggplot(df_hratt, aes(x = factor(job_satisfaction), fill = attrition)) +
geom_bar(position = "fill") +
scale_fill_manual(values = c("lightgray", "blue")) + # Specify colors for attrition categories
labs(title = "Attrition Probabilities per job satisfaction",
x = "Job satisfaction",
fill = "Attrition") +
theme_minimal(base_size = 15) +
theme(plot.title = element_text(size = 20),
axis.title.x = element_text(size = 16),
legend.title = element_text(size = 15),
legend.text = element_text(size = 15))
```
This analysis examines the association between job satisfaction and attrition, testing the hypothesis that people who are less satisfied with their job are more likely to leave. The two variables analyzed are attrition (Yes or No) and job_satisfaction (categorized as Low, Medium, High, Very High). A Chi-square test was conducted, revealing a significant association between job satisfaction and attrition. The bar chart visualizing attrition rates across different levels of job satisfaction shows that the highest attrition rate is observed in the Low job satisfaction category, followed by Medium, High, and Very High satisfaction categories in descending order. This suggests that lower job satisfaction may be associated with higher attrition rates.
**Conclusion:** The analysis supports hypothesis H12.
#### H13. People who feel less satisfied with the environment tend to leave more. **<span style="color: green;">TRUE</span>**
```{r, echo=FALSE}
# Create a contingency table
table_es <- table(df_hratt$attrition, df_hratt$environment_satisfaction)
# Perform Chi-squared test
chi_squared_test_13 <- chisq.test(table_es)