Chapter 4
HR Analytics through R: Text and Cases
R is an open source programming language or data analysis tool. It is a command line interface.
R can be integrated other languages. R is platform independent i.e., Linux, Windows or any
other operating system. R was not user-friendly so R-Studio was invented. R-Studio is an IDE
(Integrated Development Environment for R).
There are 4 windows in R Studio.
• Left Lower is R-Console Tab where you can see output.
• Upper Left is text editor where you can write command and save it for future.
• Right Side Lower Window which is used for files and graphs.
• Right Side Upper Window which is called Global Environment.
Note: Tools-Global-Apperance-Font-Theme
Through R:
(a) We can measure central tendency
(b) We can know functionality for many plots types, graphic maps, bi-plots etc.
(c) We can know probability distribution
(d) R is case sensitive
Working on R
#Creating a variable and Arithmetic Functions
x=7(Control + Enter)
x (Control + Enter)
[1] 7
y=9(Control + Enter)
y (Control + Enter)
[1] 9
x + y (Control + Enter)
[1] 16
x*y (Control + Enter)
[1] 63
#Data Types in R
✓ Numeric (data in number form)
✓ Character (data in string)
✓ Complex (original and imaginary part of number)
✓ Integer (complete number-positive or negative)
✓ Raw (vectors)
✓ Logical (true or false)
z="hello"(Control + Enter)
z (Control + Enter)
[1] "hello"
x=3-2i (Control + Enter)
x (Control + Enter)
[1] 3-2i
a=TRUE (Control + Enter)
a (Control + Enter)
[1] TRUE
class(y)
[1] "numeric"
class(x)
[1] "complex"
x=12.71
y=10
class (x+y)
[1] "numeric"
typeof(x+y)
[1] "double"
[Link](x+y)
[1] FALSE
[Link](x+y)
[1] TRUE
x="hello"
y="friends"
z=paste(x,y)
z
[1] "hello friends"
[Link](z)
[1] TRUE
Data Structure in R
There are six types of data structure: (a) Vector (b) List (c) Factor (d) Array (e) Matrix (f)
Data Frame
(a) Vector-Homogenous and unidimensional
Methods-c (), seq (), rep ()
V=c (2,4,6,7,0,12,45) [ctrl+enter]
V=c (2,4,6,7,0,12,45)
sort(V,decreasing=TRUE)
[1] 45 12 7 6 4 2 0
class (V)
[1] "numeric"
Character Vector
V=c (“Anuradha”, “Santosh”, “Satyansh”) [ctrl+enter]
[1] "Anuradha" "Santosh” “Satyansh"
Number of Items Stored in a Vector
length (V)
[1] 3
Sequence from 4 to 10 by 1.2
seq (4,10,1.2)
[1] 4.0 5.2 6.4 7.6 8.8 10.0
Sequence from 3 to 10 by 1
seq(3,10,1.0)
[1] 3 4 5 6 7 8 9 10
rep(1:3,each=2)
[1] 1 1 2 2 3 3
rep(1:3,[Link]=10)
[1] 1 2 3 1 2 3 1 2 3 1
Indexing in Vector/Position of Element inside Vector
v= c(23,40,10,19,24)
v[1]
v[4]
v[c(1,3)]
v= c(23,40,10,19,24)
> v[1]
[1] 23
> v[4]
[1] 19
> v[c(1,3)]
[1] 23 10
> v[-1]
[1] 40 10 19 24
> v[-2]
[1] 23 10 19 24
Factor Data Structure: using function called factor()
gender=c(‘female’, ‘male’)
gender=factor(gender)
> religion=factor(c("hindu","muslim","sikh","christian"))
> religion
[1] hindu muslim sikh christian
Levels: christian hindu muslim sikh
l=list (12,56,14,10L, TRUE)
>l
$double
[1] 12
$numeric
[1] 56
$integer
[1] 14
$logical
[1] 10
$<NA>
[1] TRUE
Matrix: Two dimensional arrangement of homogenous data
Function: matrix ()
Syntax: matrix (vector, nrow, ncol, byrow, dim)-pass 5 parameters while creating
matrix but it is not necessary to include all 5 parameters as mentioned above
byrow: arrangement of data in 2x2 (4 elements)
dim: dimension 2x2 (name of row and column)
m=matrix (c (2,5, -2,7), nrow=2, ncol=2, byrow=TRUE)
> m=matrix (c (2,5, -2,7), nrow=2, ncol=2, byrow=TRUE)
>m
[,1] [,2]
[1,] 2 5
[2,] -2 7
> m=matrix (c (2,5, -2,7), nrow=2, ncol=2, byrow=FALSE)
>m
[,1] [,2]
[1,] 2 -2
[2,] 5 7
v=c (4,7,1,7)
> m1=matrix (v, nrow=2)
> m2=m+m1
> m2
[,1] [,2]
[1,] 6 -1
[2,] 12 14
Naming the Dimension of a Matrix:
> m=matrix(c (2,5, -2,7),nrow=2,ncol=2,byrow=TRUE,dim=list(rowname,colname))
> rowname=c('R1','R2')
> colname=c('c1','c2')
>m
c1 c2
R1 2 5
R2 -2 7
Array: Homogenous and N-Dimensional
Function: array ()
Syntax: array (vector, dim)
> v=c (2,6,1,7)
> a=array (v, dim=c (2,2,2)) --------------2 matrix of 2 row and 2 column
>a
, ,1
[,1] [,2]
[1,] 2 1
[2,] 6 7
, ,2
[,1] [,2]
[1,] 2 1
[2,] 6 7
v1=c (9,10,24,57)
a1=array (c (v, v1), dim=c (2,2,3)) --------------3 matrix of 2 row and 2 column
a1
, ,1
[,1] [,2]
[1,] 2 1
[2,] 6 7
, ,2
[,1] [,2]
[1,] 9 24
[2,] 10 57
, ,3
[,1] [,2]
[1,] 2 1
[2,] 6 7
Indexing in Matrix: asking element of 1st row and 2nd column
> m [1,2]
[1] 5
> m [2,1]
[1] -2
Changing Value in Matrix:
> m [2,] =c (4,10)
>m
c1 c2
R1 2 5
R2 4 10
Data Frame: heterogeneous 2 dimensional matrix
Function: dataframe ()
Syntax: data. frame (Vectors, StringAsFactor)
name=c('santosh','ajay','geeta','sajja')
gender=c('male','male','female','female')
hobby=c('reading','writing','singing','dancing')
rajagiri=[Link](name,gender,hobby)
rajagiri
name gender hobby
1 santosh male reading
2 ajay male writing
3 geeta female singing
4 sajja female dancing
pgdm=[Link](ID=c(2301,2302,2303,2304),Name=c('Mohan','Rohan','Ruchi','Ary
a'),Age=c(29,21,20,22),StringAsFactor=FALSE)
pgdm
ID Name Age StringAsFactor
1 2301 Mohan 29 FALSE
2 2302 Rohan 21 FALSE
3 2303 Ruchi 20 FALSE
4 2304 Arya 22 FALSE
class(pgdm)
[1] "[Link]"
typeof(pgdm)
[1] "list"
Adding Row to a Dataframe:
MBA=[Link](ID=c(2301,2302,2303,2304),Name=c('Mohan','Rohan','Ruchi','Ary
a'),Age=c(29,21,20,22),StringAsFactor=FALSE)
MBA
ID Name Age StringAsFactor
1 2301 Mohan 29 FALSE
2 2302 Rohan 21 FALSE
3 2303 Ruchi 20 FALSE
4 2304 Arya 22 FALSE
> HRM=rbind(pgdm,MBA)
> HRM
ID Name Age StringAsFactor
1 2301 Mohan 29 FALSE
2 2302 Rohan 21 FALSE
3 2303 Ruchi 20 FALSE
4 2304 Arya 22 FALSE
5 2301 Mohan 29 FALSE
6 2302 Rohan 21 FALSE
7 2303 Ruchi 20 FALSE
8 2304 Arya 22 FALSE
Functions: Objects that help us to do multiple operations
Type: In-built functions (uploaded in library of R by developers) and user-defined
functions
X=3
> y='hello'
> z='world'
> paste(y,z)
[1] "hello world"
In-Built Functions
str (), seq (), rep (), list (), matrix (), array (), data. frame (), is. numeric (). as. numeric
(typecasting)
Descriptive Statistics: Describe or Summarize Data
Measurement of Central Tendency: We can find single value explaining whole data
such as mean, mode, median
Measure of Dispersion-SD, Variance
Measure of Distribution-Skewness, Kurtosis
X=c (10,20,30,40,50)
X
mean(X)
[1] 30
X=c (10,20,30,10,40,50)
X
mode(X)
var (X)
sd (X)
User-defined Function: for, if, while loop
Function to get square of a number
Square=function(x)
+ {return=(x*x)}
> Square (3)
> cat (Square (3))
9
Simple Interest
si=function (P, R, T)
{return=(P*R*T/100)}
cat (si (3,2,3))
0.18
Area of Rectangle= (length=5, width=5)
area=function (l, b)
{return=(l*b)}
cat (area (5,5))
Binomial Distribution
dbinom (x, size, prob, lower. tail=TRUE) -------prob values of exact outcome
pbinom---------------cumulative i.e., less than
qbinom-------------find the value of x when prob is given
rbinom (n, size, prob) ------------generate n random numbers which follow binomial
Ex-find prob of getting exactly 5 heads when a coin is tossed 10 times
dbinom (5,10,1/2)
[1] 0.2460938
Solution for no head
dbinom (0,4,1/2)
[1] 0.0625
Normal Distribution
Mean=0, SD=1, Skewness and Kurtosis=0, Bell-shaped Curve, Area under Curve =1,
Median=Mode=Mean, Centre of Curve will be Mean value
pnorm (39,30,4,TRUE)
[1] 0.9877755
p(x>21)
pnorm (21,30,4,F)
[1] 0.9877755
Non-Parametric Test: Chi-Square Test, Man Whitney, Spearman Correlation
Inferential Statistics-It helps to infer population parameter using sample
We always test null hypotheses using statistical tests. Tests are based on qualitative data
i.e., categorical data and there is no consideration of normal distribution of data
Types of Chi-square-goodness of fit and independence of attributes
Chi-square=Sum (O-E)2 /E, O=Observed frequency, E=Expected frequency,
E=Average of expected frequency
Parametric Tests: Test which consider the parameter of population and also concerned
about the normal distribution of data. Example-t Test, ANOVA, Regression,
Correlation
Example-A company want which colour to be launched? Survey says that
100,80,95,115,120,50 consumers preferred pink, yellow, white, blue, red, orange
Create observed frequency vector
Colour=c (100,80,95,115,120,50)
Expected=mean (colour)
Expected
H0: There is no significant difference between observed and expected frequency of
colour
[Link] (vector of observed frequency, vector of probability)
[Link] (colour, p=rep (1/6,6)
Colour=c (100,80,95,115,120,50)
Expected=mean (Colour)
Expected
[1] 93.33333
[Link] (Colour,p=rep (1/6,6))
Chi-squared test for given probabilities
data: Colour
X-squared = 35.179, df = 5, p-value = 1.386e-06
If p value is less than 0.5, do not accept null hypothesis. So, in this case, p value is less
than 0.5, so null hypothesis is not accepted. It means there is significant difference
colour preference of consumers.
Example: A company want to test whether the footfall in a shopping mall in the last
week is uniform throughout the week
Independence of Attribute: Two categorical Variable
H0: There is no association between categorical variable 1 and categorical variable 2
Example: Whether the smoking habit is independent of gender?
Gender=c (“f”, “m”, “m”, “f”, “m”)
length (gender)
Smoking-Habit=c (“y”, “y”, “n”, “n”, “y”)
Data=data. frame (Gender, Smoking-Habit)
Contingency Table: Two-way table which gives count across categories of both
categorical variables
Tb1=table(data$gender,data$Smoking_Habit)
data=[Link] (gender, Smoking_Habit)
Tb1=table(data$gender,data$Smoking_Habit)
Tb1
ny
f11
m12
[Link] (Tb1)
Pearson's Chi-squared test with Yates'
continuity correction
data: Tb1
X-squared = 0, df = 1, p-value = 1
p -value is more than 0.5, so null hypothesis is accepted. It means smoking and gender
are independent.
Parametric Test (t-Test): Used to find significant mean difference between
sample and population mean
Significance Level: 10%,5%,1%
One-Sample t-Test: Only one Variable
Example: Whether there is significand difference in sample and poulation IQ
Assumptions:
DV should be numeric and continuous
DV should be normally distributed
There should be no outlier in DV
IQ=c (120,112,103,114,106,111,109,104,109,108)
H0: The variable is normally distributed
[Link] (IQ)
Shapiro-Wilk normality test
data: IQ
W = 0.95411, p-value = 0.7172
As p-value is greater than 0.05, Accept Null Hypothesis (H0). The variable is normally
distributed.
qqnorm(IQ)
qqline(IQ)
qqline(IQ,col='red')
For Outlier Checking: Box Plot is used
boxplot(IQ)
5 elements: Median, 1st quartile,3rd Quartile, Upper and Lower Whisker
If there is outlier, circles will cross Whiskers.
One Sample t-Test
[Link] (vector, population mean, alpha, alternative/one-tail or two tail)
Suppose according to research report population mean is 100.
[Link](IQ,mu=100,alpha=0.05,alternative='[Link]')
One Sample t-test, data: IQ
t = 6.0528, df = 9, p-value = 0.0001898
alternative hypothesis: true mean is not equal to 100
95 percent confidence interval:
106.0121 113.1879
sample estimates:
mean of x
109.6
As p-value is less than 0.05, reject null hypothesis. There is significant difference between
population and sample mean.
Independent Sample t-Test:
• Two variables are required (IV and DV)
• IV should be categorical with two levels
• DV should be continuous and numeric
Assumptions:
• Observations should be independent to each other i.e., from one respondent collect
data only once
• DV should be normally distributed
• There should be no significant outlier in DV
• There should be homogeneity of variance in DV corresponding to categories of IV
Example:
Whether there is significant difference in the mean marks of male and female students?
Gender=factor(c("M","F","M","F","M","F"))
length(Gender)
Marks=c(20,30,40,50,60,70)
[Link](Marks)
Shapiro-Wilk normality test
data: Marks
W = 0.98189, p-value = 0.9606
As p=value is greater than 0.05, accept null hypothesis. Variable (DV) is normally
distributed.
qqnorm(Marks)
qqline(Marks)
qqline(Marks,col='blue')
boxplot(Marks)
[Link](Marks~Gender)
Dependent Sample t-Test: For single sample, collect data twice (Before-After, Pre-Post)
Assumptions
• The variable should be continuous or numerical
• The difference between pre and post data should be normally distributed
• There should be no outlier in difference
Example: Weight of Respondents Before and After Diet Plan
Before=c(65,89,95,100)
After=c(82,79,64,75)
Difference=Before-After
Difference
[1] -17 10 31 25
[Link](Difference)
Shapiro-Wilk normality test
data: Difference
W = 0.91587, p-value = 0.5141
As p-value is greater than 0.05, accept null hypothesis i.e., difference is normally distributed.
boxplot(Difference)
[Link](Before,After,paired=T)
Paired t-test
data: Before and After
t = 1.1445, df = 3, p-value = 0.3355
alternative hypothesis: true mean difference is not equal to 0
95 percent confidence interval:
-21.81296 46.31296
sample estimates:
mean difference
12.25
As p-value is greater than 0.05, accept null hypothesis. There is no significant difference in
weight before and after diet plan.
ANOVA: Analysis of Variance of Mean
One-Way: Independent sample t-test
Assumptions
• Observation should be independent
• The DV should be normally distributed
• There should be no outlier in DV corresponding to the categories of IV
• There should be homogeneity of variance (Levene Test)
Example: Whether the mean income of Businessmen, Servicemen, and Retired people is
equal?
Occupation with three groups (Categorical)
Income: Numeric/Continuous
H0: There is no significant difference in the mean income of people on the basis of their
occupation
Income=c(20000,30000,40000,50000,60000)
factor(c(20000,30000,40000,50000,60000))
[Link](Income)
Shapiro-Wilk normality test
data: Income
W = 0.98676, p-value = 0.9672
As p-value is greater than 0.05, accept null hypothesis. There is no significant difference in
income on the basis of occupation.
qqnorm(Income)
qqline(Income,col='red')
boxplot(Income~Occupation)
Homogeneity of Variance
library(car)
result=aov(Income~Occupation)
ANOVA cannot tell in which pair, mean difference exists. So, go for multiple comparison
(PostHoc/Tukey HSD)
Two-Way ANOVA
boxplot (Income ~Ocuupation+Gender)
result=aov(Income ~Occupation+Gender)
Summary(result)
Note: Excel Data: Text-to-Colum (Remove $ from Salary)
Two-Way: One DV (Continuous/Numeric) and Two IVs (Categorical)
Correlation:
• Strength and Direction of Relationship between Variables
• There is no DV and IV
• Two variables are continuous and numeric
Example: What is the correlation between sugar price and sales of sweet?
Price=c(40,42,40)
Sales=c(20,30,40)
[Link](Sales, Price)
Pearson's product-moment correlation
data: Sales and Price
t = 0, df = 1, p-value = 1
alternative hypothesis: true correlation is not equal to 0
sample estimates:
cor 0
As p-value is greater than 0.05, accept null hypothesis There is no correlation between Sales
and Price
Regression
It is algebraic relationship between variables.
It helps to forecast DV using IV
To find impact of IV on DV
Regression’
Type of Regression
• Simple Linear: Two numeric value of IV and DV
• Check normality and outlier in DV
• Whether the residuals are independent. Residual is difference between actual and
expected value. In good model, residual should be minimum.
• Y=a+bX+e, Y=DV, X=IV, a=intercept, b=slope of IV
Example-
Sales=c(20000,22000,28000,30000)
AdvExpenditure=c(20000,30,000,10,000)
H0: There is no significant impact of advertisement expenditure on sales
[Link](Sales)
Shapiro-Wilk normality test
data: Sales
W = 0.91099, p-value = 0.4877
As p-value is greater than 0.05, accept null hypothesis. So, normal distribution.
hist(Sales)
y=mean(Sales)
S=sd(Sales)
X=dnorm(Sales,Y,S)
curve(dnorm(x,y,S),from=0,to=50,add=TRUE,col='red')
curve(X,Y,S,add=TRUE)
model1=lm(Sales~AdvExpenditure)
summary(model1)