R Markdown

Chapter#1 : Descriptive Statistics and Graphics

Import your data into R Here, we’ll use the built-in R data set named iris.

# Store the data in the variable my_data
my_data <- iris

Check your data

You can inspect your data using the functions head() and tails(), which will display the first and the last part of the data, respectively.

# Print the first 6 rows
head(my_data, 6)
##   Sepal.Length Sepal.Width Petal.Length Petal.Width Species
## 1          5.1         3.5          1.4         0.2  setosa
## 2          4.9         3.0          1.4         0.2  setosa
## 3          4.7         3.2          1.3         0.2  setosa
## 4          4.6         3.1          1.5         0.2  setosa
## 5          5.0         3.6          1.4         0.2  setosa
## 6          5.4         3.9          1.7         0.4  setosa

Measure of variablity

Measures of variability gives how “spread out” the data are.

Range: minimum & maximum

# Compute the minimum value
min(my_data$Sepal.Length)
## [1] 4.3
# Compute the maximum value
max(my_data$Sepal.Length)
## [1] 7.9
# Range
range(my_data$Sepal.Length)
## [1] 4.3 7.9

Interquartile range

R function:

quantile(my_data$Sepal.Length)
##   0%  25%  50%  75% 100% 
##  4.3  5.1  5.8  6.4  7.9
#To compute deciles (0.1, 0.2, 0.3, …., 0.9), use this:

quantile(my_data$Sepal.Length, seq(0, 1, 0.1))
##   0%  10%  20%  30%  40%  50%  60%  70%  80%  90% 100% 
## 4.30 4.80 5.00 5.27 5.60 5.80 6.10 6.30 6.52 6.90 7.90
#To compute the interquartile range, type this:

IQR(my_data$Sepal.Length)
## [1] 1.3

Variance and standard deviation

# Compute the variance
var(my_data$Sepal.Length)
## [1] 0.6856935
# Compute the standard deviation =
# square root of th variance
sd(my_data$Sepal.Length)
## [1] 0.8280661

Median absolute deviation

# Compute the median
median(my_data$Sepal.Length)
## [1] 5.8
# Compute the median absolute deviation
mad(my_data$Sepal.Length)
## [1] 1.03782

summary() function

summary(my_data$Sepal.Length)
##    Min. 1st Qu.  Median    Mean 3rd Qu.    Max. 
##   4.300   5.100   5.800   5.843   6.400   7.900
summary(my_data, digits = 1)
##   Sepal.Length  Sepal.Width  Petal.Length  Petal.Width        Species  
##  Min.   :4     Min.   :2    Min.   :1     Min.   :0.1   setosa    :50  
##  1st Qu.:5     1st Qu.:3    1st Qu.:2     1st Qu.:0.3   versicolor:50  
##  Median :6     Median :3    Median :4     Median :1.3   virginica :50  
##  Mean   :6     Mean   :3    Mean   :4     Mean   :1.2                  
##  3rd Qu.:6     3rd Qu.:3    3rd Qu.:5     3rd Qu.:1.8                  
##  Max.   :8     Max.   :4    Max.   :7     Max.   :2.5
# Compute the mean of each column
sapply(my_data[, -5], mean)
## Sepal.Length  Sepal.Width Petal.Length  Petal.Width 
##     5.843333     3.057333     3.758000     1.199333
# Compute quartiles
sapply(my_data[, -5], quantile)
##      Sepal.Length Sepal.Width Petal.Length Petal.Width
## 0%            4.3         2.0         1.00         0.1
## 25%           5.1         2.8         1.60         0.3
## 50%           5.8         3.0         4.35         1.3
## 75%           6.4         3.3         5.10         1.8
## 100%          7.9         4.4         6.90         2.5

Comparing Means in R One-Sample T-test in R

set.seed(1234)
my_data <- data.frame(
  name = paste0(rep("M_", 10), 1:10),
  weight = round(rnorm(10, 20, 2), 1)
)
head(my_data, 10)
##    name weight
## 1   M_1   17.6
## 2   M_2   20.6
## 3   M_3   22.2
## 4   M_4   15.3
## 5   M_5   20.9
## 6   M_6   21.0
## 7   M_7   18.9
## 8   M_8   18.9
## 9   M_9   18.9
## 10 M_10   18.2
# Statistical summaries of weight
summary(my_data$weight)
##    Min. 1st Qu.  Median    Mean 3rd Qu.    Max. 
##   15.30   18.38   18.90   19.25   20.82   22.20

Visualize your data using box plots

library(ggpubr)
## Warning: package 'ggpubr' was built under R version 4.3.2
## Loading required package: ggplot2
ggboxplot(my_data$weight, 
          ylab = "Weight (g)", xlab = FALSE,
          ggtheme = theme_minimal())

Preleminary test to check one-sample t-test assumptions

shapiro.test(my_data$weight) # => p-value = 0.6993
## 
##  Shapiro-Wilk normality test
## 
## data:  my_data$weight
## W = 0.9526, p-value = 0.6993
# One-sample t-test
res <- t.test(my_data$weight, mu = 25)
# Printing the results
res 
## 
##  One Sample t-test
## 
## data:  my_data$weight
## t = -9.0783, df = 9, p-value = 7.953e-06
## alternative hypothesis: true mean is not equal to 25
## 95 percent confidence interval:
##  17.8172 20.6828
## sample estimates:
## mean of x 
##     19.25

One-Sample Wilcoxon Signed Rank Test in R

# One-sample wilcoxon test
res <- wilcox.test(my_data$weight, mu = 25)
## Warning in wilcox.test.default(my_data$weight, mu = 25): cannot compute exact
## p-value with ties
# Printing the results
res 
## 
##  Wilcoxon signed rank test with continuity correction
## 
## data:  my_data$weight
## V = 0, p-value = 0.005793
## alternative hypothesis: true location is not equal to 25
# print only the p-value
res$p.value
## [1] 0.005793045

Unpaired Two-Samples T-test in R

# Data in two numeric vectors
women_weight <- c(38.9, 61.2, 73.3, 21.8, 63.4, 64.6, 48.4, 48.8, 48.5)
men_weight <- c(67.8, 60, 63.4, 76, 89.4, 73.3, 67.3, 61.3, 62.4) 
# Create a data frame
my_data <- data.frame( 
                group = rep(c("Woman", "Man"), each = 9),
                weight = c(women_weight,  men_weight)
                )
# Print all data
print(my_data)
##    group weight
## 1  Woman   38.9
## 2  Woman   61.2
## 3  Woman   73.3
## 4  Woman   21.8
## 5  Woman   63.4
## 6  Woman   64.6
## 7  Woman   48.4
## 8  Woman   48.8
## 9  Woman   48.5
## 10   Man   67.8
## 11   Man   60.0
## 12   Man   63.4
## 13   Man   76.0
## 14   Man   89.4
## 15   Man   73.3
## 16   Man   67.3
## 17   Man   61.3
## 18   Man   62.4
# Plot weight by group and color by group
library("ggpubr")
ggboxplot(my_data, x = "group", y = "weight", 
          color = "group", palette = c("#00AFBB", "#E7B800"),
        ylab = "Weight", xlab = "Groups")

Preleminary test to check independent t-test assumptions

# Shapiro-Wilk normality test for Men's weights
with(my_data, shapiro.test(weight[group == "Man"]))# p = 0.1
## 
##  Shapiro-Wilk normality test
## 
## data:  weight[group == "Man"]
## W = 0.86425, p-value = 0.1066
# Shapiro-Wilk normality test for Women's weights
with(my_data, shapiro.test(weight[group == "Woman"])) # p = 0.6
## 
##  Shapiro-Wilk normality test
## 
## data:  weight[group == "Woman"]
## W = 0.94266, p-value = 0.6101
# T_test
res.ftest <- var.test(weight ~ group, data = my_data)
res.ftest
## 
##  F test to compare two variances
## 
## data:  weight by group
## F = 0.36134, num df = 8, denom df = 8, p-value = 0.1714
## alternative hypothesis: true ratio of variances is not equal to 1
## 95 percent confidence interval:
##  0.08150656 1.60191315
## sample estimates:
## ratio of variances 
##          0.3613398

Unpaired Two-Samples Wilcoxon Test in R

res <- wilcox.test(women_weight, men_weight)
## Warning in wilcox.test.default(women_weight, men_weight): cannot compute exact
## p-value with ties
res
## 
##  Wilcoxon rank sum test with continuity correction
## 
## data:  women_weight and men_weight
## W = 15, p-value = 0.02712
## alternative hypothesis: true location shift is not equal to 0

Paired Samples T-test in R

 #Data in two numeric vectors
# ++++++++++++++++++++++++++
# Weight of the mice before treatment
before <-c(200.1, 190.9, 192.7, 213, 241.4, 196.9, 172.2, 185.5, 205.2, 193.7)
# Weight of the mice after treatment
after <-c(392.9, 393.2, 345.1, 393, 434, 427.9, 422, 383.9, 392.3, 352.2)
# Create a data frame
my_data <- data.frame( 
                group = rep(c("before", "after"), each = 10),
                weight = c(before,  after)
                )
# Print all data
print(my_data)
##     group weight
## 1  before  200.1
## 2  before  190.9
## 3  before  192.7
## 4  before  213.0
## 5  before  241.4
## 6  before  196.9
## 7  before  172.2
## 8  before  185.5
## 9  before  205.2
## 10 before  193.7
## 11  after  392.9
## 12  after  393.2
## 13  after  345.1
## 14  after  393.0
## 15  after  434.0
## 16  after  427.9
## 17  after  422.0
## 18  after  383.9
## 19  after  392.3
## 20  after  352.2
library("dplyr")
## Warning: package 'dplyr' was built under R version 4.3.2
## 
## 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
group_by(my_data, group) %>%
  summarise(
    count = n(),
    mean = mean(weight, na.rm = TRUE),
    sd = sd(weight, na.rm = TRUE)
  )
## # A tibble: 2 × 4
##   group  count  mean    sd
##   <chr>  <int> <dbl> <dbl>
## 1 after     10  394.  29.4
## 2 before    10  199.  18.5
# Compute t-test
res <- t.test(before, after, paired = TRUE)
res
## 
##  Paired t-test
## 
## data:  before and after
## t = -20.883, df = 9, p-value = 6.2e-09
## alternative hypothesis: true mean difference is not equal to 0
## 95 percent confidence interval:
##  -215.5581 -173.4219
## sample estimates:
## mean difference 
##         -194.49

Paired Samples Wilcoxon Test in R

# Compute t-test
res <- wilcox.test(weight ~ group, data = my_data, paired = TRUE)
res
## 
##  Wilcoxon signed rank exact test
## 
## data:  weight by group
## V = 55, p-value = 0.001953
## alternative hypothesis: true location shift is not equal to 0
# print only the p-value
res$p.value
## [1] 0.001953125

One-Way ANOVA Test in R

my_data <- PlantGrowth
set.seed(1234)
dplyr::sample_n(my_data, 10)
##    weight group
## 1    6.15  trt2
## 2    3.83  trt1
## 3    5.29  trt2
## 4    5.12  trt2
## 5    4.50  ctrl
## 6    4.17  trt1
## 7    5.87  trt1
## 8    5.33  ctrl
## 9    5.26  trt2
## 10   4.61  ctrl
my_data$group <- ordered(my_data$group,
                         levels = c("ctrl", "trt1", "trt2"))
library(dplyr)
group_by(my_data, group) %>%
  summarise(
    count = n(),
    mean = mean(weight, na.rm = TRUE),
    sd = sd(weight, na.rm = TRUE)
  )
## # A tibble: 3 × 4
##   group count  mean    sd
##   <ord> <int> <dbl> <dbl>
## 1 ctrl     10  5.03 0.583
## 2 trt1     10  4.66 0.794
## 3 trt2     10  5.53 0.443
# Compute the analysis of variance
aov(weight ~ group, data = my_data)
## Call:
##    aov(formula = weight ~ group, data = my_data)
## 
## Terms:
##                    group Residuals
## Sum of Squares   3.76634  10.49209
## Deg. of Freedom        2        27
## 
## Residual standard error: 0.6233746
## Estimated effects are balanced

Two-Way ANOVA Test in R

# Store the data in the variable my_data
my_data <- ToothGrowth
# Show a random sample
set.seed(1234)
dplyr::sample_n(my_data, 10)
##     len supp dose
## 1  21.5   VC  2.0
## 2  17.3   VC  1.0
## 3  27.3   OJ  2.0
## 4  18.5   VC  2.0
## 5   8.2   OJ  0.5
## 6  26.4   OJ  1.0
## 7  25.8   OJ  1.0
## 8   5.2   VC  0.5
## 9   6.4   VC  0.5
## 10  9.4   OJ  0.5
# Check the structure
str(my_data)
## 'data.frame':    60 obs. of  3 variables:
##  $ len : num  4.2 11.5 7.3 5.8 6.4 10 11.2 11.2 5.2 7 ...
##  $ supp: Factor w/ 2 levels "OJ","VC": 2 2 2 2 2 2 2 2 2 2 ...
##  $ dose: num  0.5 0.5 0.5 0.5 0.5 0.5 0.5 0.5 0.5 0.5 ...
# Convert dose as a factor and recode the levels
# as "D0.5", "D1", "D2"
my_data$dose <- factor(my_data$dose, 
                  levels = c(0.5, 1, 2),
                  labels = c("D0.5", "D1", "D2"))
head(my_data)
##    len supp dose
## 1  4.2   VC D0.5
## 2 11.5   VC D0.5
## 3  7.3   VC D0.5
## 4  5.8   VC D0.5
## 5  6.4   VC D0.5
## 6 10.0   VC D0.5
table(my_data$supp, my_data$dose)
##     
##      D0.5 D1 D2
##   OJ   10 10 10
##   VC   10 10 10
# Box plot with multiple groups
# +++++++++++++++++++++
# Plot tooth length ("len") by groups ("dose")
# Color box plot by a second group: "supp"
library("ggpubr")
ggboxplot(my_data, x = "dose", y = "len", color = "supp",
          palette = c("#00AFBB", "#E7B800"))

res.aov2 <- aov(len ~ supp + dose, data = my_data)
summary(res.aov2)
##             Df Sum Sq Mean Sq F value   Pr(>F)    
## supp         1  205.4   205.4   14.02 0.000429 ***
## dose         2 2426.4  1213.2   82.81  < 2e-16 ***
## Residuals   56  820.4    14.7                     
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
# Two-way ANOVA with interaction effect
# These two calls are equivalent
res.aov3 <- aov(len ~ supp * dose, data = my_data)
res.aov3 <- aov(len ~ supp + dose + supp:dose, data = my_data)
summary(res.aov3)
##             Df Sum Sq Mean Sq F value   Pr(>F)    
## supp         1  205.4   205.4  15.572 0.000231 ***
## dose         2 2426.4  1213.2  92.000  < 2e-16 ***
## supp:dose    2  108.3    54.2   4.107 0.021860 *  
## Residuals   54  712.1    13.2                     
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Comparing Variances in R F-Test: Compare Two Variances in R

# F-test
res.ftest <- var.test(len ~ supp, data = my_data)
res.ftest
## 
##  F test to compare two variances
## 
## data:  len by supp
## F = 0.6386, num df = 29, denom df = 29, p-value = 0.2331
## alternative hypothesis: true ratio of variances is not equal to 1
## 95 percent confidence interval:
##  0.3039488 1.3416857
## sample estimates:
## ratio of variances 
##          0.6385951

Compare Multiple Sample Variances in R

res <- bartlett.test(weight ~ group, data = PlantGrowth)
res
## 
##  Bartlett test of homogeneity of variances
## 
## data:  weight by group
## Bartlett's K-squared = 2.8786, df = 2, p-value = 0.2371
fligner.test(weight ~ group, data = PlantGrowth)
## 
##  Fligner-Killeen test of homogeneity of variances
## 
## data:  weight by group
## Fligner-Killeen:med chi-squared = 2.3499, df = 2, p-value = 0.3088

Comparing Proportions in R One-Proportion Z-Test in R

res <- prop.test(x = 95, n = 160, p = 0.5, 
                 correct = FALSE)
# Printing the results
res 
## 
##  1-sample proportions test without continuity correction
## 
## data:  95 out of 160, null probability 0.5
## X-squared = 5.625, df = 1, p-value = 0.01771
## alternative hypothesis: true p is not equal to 0.5
## 95 percent confidence interval:
##  0.5163169 0.6667870
## sample estimates:
##       p 
## 0.59375

Compute two-proportions z-test in R

res <- prop.test(x = c(490, 400), n = c(500, 500))
# Printing the results
res 
## 
##  2-sample test for equality of proportions with continuity correction
## 
## data:  c(490, 400) out of c(500, 500)
## X-squared = 80.909, df = 1, p-value < 2.2e-16
## alternative hypothesis: two.sided
## 95 percent confidence interval:
##  0.1408536 0.2191464
## sample estimates:
## prop 1 prop 2 
##   0.98   0.80

Multiple REgression:

CGPA <- c(2.8, 2.5, 3.2, 3.5, 3.1, 2.9, 2.6, 2.7, 2.98, 3, 3.1, 3.7, 3.6, 3.56, 3.8, 3.76, 3.2, 2.7, 2.8, 3.2, 3.1, 3, 3.7, 3.2, 3)
AGE <- c(21, 20, 21, 20, 21, 21, 20, 10, 20, 21, 22, 22, 21, 20, 19, 21, 20, 22, 19, 21, 20, 22, 19, 19, 21)
INTER_MARKS <- c(876, 870, 970, 930, 760, 560, 660, 780, 980, 1000, 1020, 995, 1005, 1050, 1075, 2070, 920, 910, 850, 670, 520, 760, 720, 920, 1030)
INCOME <- c(15000, 11000, 10000, 20000, 30000, 35000, 19000, 15000, 17000, 40000, 50000, 30000, 20000, 25000, 20000, 17000, 18000, 16000, 12000, 13000, 35000, 32000, 28000, 25000, 22000)
GPA_1 <- c(2.7, 2.8, 3.5, 3.9, 3.8, 3.2, 3.1, 2.9, 2.8, 2.75, 2.6, 2.5, 2.9, 3, 3.2, 3.6, 3.6, 3.9, 3.7, 3.5, 3.4, 3.3, 3.1, 3.2, 3.3)

#---------------------------------------------------
#               Direct method
model <- lm(CGPA ~ AGE + INTER_MARKS + INCOME + GPA_1)
model
## 
## Call:
## lm(formula = CGPA ~ AGE + INTER_MARKS + INCOME + GPA_1)
## 
## Coefficients:
## (Intercept)          AGE  INTER_MARKS       INCOME        GPA_1  
##   1.977e+00    4.495e-03    6.544e-04    9.293e-06    8.326e-02
summary(model)
## 
## Call:
## lm(formula = CGPA ~ AGE + INTER_MARKS + INCOME + GPA_1)
## 
## Residuals:
##     Min      1Q  Median      3Q     Max 
## -0.4717 -0.2247 -0.1194  0.2778  0.6480 
## 
## Coefficients:
##              Estimate Std. Error t value Pr(>|t|)  
## (Intercept) 1.977e+00  8.552e-01   2.312   0.0316 *
## AGE         4.495e-03  3.382e-02   0.133   0.8956  
## INTER_MARKS 6.544e-04  2.616e-04   2.502   0.0212 *
## INCOME      9.293e-06  8.294e-06   1.121   0.2757  
## GPA_1       8.326e-02  1.906e-01   0.437   0.6669  
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## Residual standard error: 0.3541 on 20 degrees of freedom
## Multiple R-squared:  0.2718, Adjusted R-squared:  0.1261 
## F-statistic: 1.866 on 4 and 20 DF,  p-value: 0.156
confint(model)
##                     2.5 %       97.5 %
## (Intercept)  1.931294e-01 3.761014e+00
## AGE         -6.604341e-02 7.503437e-02
## INTER_MARKS  1.087427e-04 1.200091e-03
## INCOME      -8.006526e-06 2.659343e-05
## GPA_1       -3.143176e-01 4.808336e-01
#---------------------------------------------------
#               Matrix approach

# Organize the data into matrices
CGPA <- c(2.8, 2.5, 3.2, 3.5, 3.1, 2.9, 2.6, 2.7, 2.98, 3, 3.1, 3.7, 3.6, 3.56, 3.8, 3.76, 3.2, 2.7, 2.8, 3.2, 3.1, 3, 3.7, 3.2, 3)
AGE <- c(21, 20, 21, 20, 21, 21, 20, 10, 20, 21, 22, 22, 21, 20, 19, 21, 20, 22, 19, 21, 20, 22, 19, 19, 21)
INTER_MARKS <- c(876, 870, 970, 930, 760, 560, 660, 780, 980, 1000, 1020, 995, 1005, 1050, 1075, 2070, 920, 910, 850, 670, 520, 760, 720, 920, 1030)
INCOME <- c(15000, 11000, 10000, 20000, 30000, 35000, 19000, 15000, 17000, 40000, 50000, 30000, 20000, 25000, 20000, 17000, 18000, 16000, 12000, 13000, 35000, 32000, 28000, 25000, 22000)
GPA_1 <- c(2.7, 2.8, 3.5, 3.9, 3.8, 3.2, 3.1, 2.9, 2.8, 2.75, 2.6, 2.5, 2.9, 3, 3.2, 3.6, 3.6, 3.9, 3.7, 3.5, 3.4, 3.3, 3.1, 3.2, 3.3)

# Create a matrix X with independent variables
X <- cbind(AGE, INTER_MARKS, INCOME, GPA_1)
X
##       AGE INTER_MARKS INCOME GPA_1
##  [1,]  21         876  15000  2.70
##  [2,]  20         870  11000  2.80
##  [3,]  21         970  10000  3.50
##  [4,]  20         930  20000  3.90
##  [5,]  21         760  30000  3.80
##  [6,]  21         560  35000  3.20
##  [7,]  20         660  19000  3.10
##  [8,]  10         780  15000  2.90
##  [9,]  20         980  17000  2.80
## [10,]  21        1000  40000  2.75
## [11,]  22        1020  50000  2.60
## [12,]  22         995  30000  2.50
## [13,]  21        1005  20000  2.90
## [14,]  20        1050  25000  3.00
## [15,]  19        1075  20000  3.20
## [16,]  21        2070  17000  3.60
## [17,]  20         920  18000  3.60
## [18,]  22         910  16000  3.90
## [19,]  19         850  12000  3.70
## [20,]  21         670  13000  3.50
## [21,]  20         520  35000  3.40
## [22,]  22         760  32000  3.30
## [23,]  19         720  28000  3.10
## [24,]  19         920  25000  3.20
## [25,]  21        1030  22000  3.30
# Create a vector Y with the dependent variable
Y <- CGPA
Y
##  [1] 2.80 2.50 3.20 3.50 3.10 2.90 2.60 2.70 2.98 3.00 3.10 3.70 3.60 3.56 3.80
## [16] 3.76 3.20 2.70 2.80 3.20 3.10 3.00 3.70 3.20 3.00
# Calculate X transpose
X_transpose <- t(X)
X_transpose
##                [,1]    [,2]    [,3]    [,4]    [,5]    [,6]    [,7]    [,8]
## AGE            21.0    20.0    21.0    20.0    21.0    21.0    20.0    10.0
## INTER_MARKS   876.0   870.0   970.0   930.0   760.0   560.0   660.0   780.0
## INCOME      15000.0 11000.0 10000.0 20000.0 30000.0 35000.0 19000.0 15000.0
## GPA_1           2.7     2.8     3.5     3.9     3.8     3.2     3.1     2.9
##                [,9]    [,10]   [,11]   [,12]   [,13] [,14]   [,15]   [,16]
## AGE            20.0    21.00    22.0    22.0    21.0    20    19.0    21.0
## INTER_MARKS   980.0  1000.00  1020.0   995.0  1005.0  1050  1075.0  2070.0
## INCOME      17000.0 40000.00 50000.0 30000.0 20000.0 25000 20000.0 17000.0
## GPA_1           2.8     2.75     2.6     2.5     2.9     3     3.2     3.6
##               [,17]   [,18]   [,19]   [,20]   [,21]   [,22]   [,23]   [,24]
## AGE            20.0    22.0    19.0    21.0    20.0    22.0    19.0    19.0
## INTER_MARKS   920.0   910.0   850.0   670.0   520.0   760.0   720.0   920.0
## INCOME      18000.0 16000.0 12000.0 13000.0 35000.0 32000.0 28000.0 25000.0
## GPA_1           3.6     3.9     3.7     3.5     3.4     3.3     3.1     3.2
##               [,25]
## AGE            21.0
## INTER_MARKS  1030.0
## INCOME      22000.0
## GPA_1           3.3
# Calculate X transpose times X
X_transpose_X <- X_transpose %*% X
X_transpose_X
##                     AGE INTER_MARKS     INCOME        GPA_1
## AGE            10249.00    462966.0 1.1723e+07    1616.6500
## INTER_MARKS   462966.00  22928751.0 5.1657e+08   73603.2000
## INCOME      11723000.00 516570000.0 1.5595e+10 1814600.0000
## GPA_1           1616.65     73603.2 1.8146e+06     261.6125
# Calculate the inverse of X transpose times X
X_transpose_X_inv <- solve(X_transpose_X)
X_transpose_X_inv
##                       AGE   INTER_MARKS        INCOME         GPA_1
## AGE          6.682802e-03 -2.150337e-05 -1.088708e-06 -2.769541e-02
## INTER_MARKS -2.150337e-05  5.219324e-07  2.593845e-09 -3.195286e-05
## INCOME      -1.088708e-06  2.593845e-09  5.115760e-10  2.449571e-06
## GPA_1       -2.769541e-02 -3.195286e-05  2.449571e-06  1.669669e-01
# Calculate X transpose times Y
X_transpose_Y <- X_transpose %*% Y
X_transpose_Y
##                   [,1]
## AGE            1587.06
## INTER_MARKS   73291.90
## INCOME      1823580.00
## GPA_1           252.74
# Calculate the coefficients beta
beta <- X_transpose_X_inv %*% X_transpose_Y

# Display the coefficients
print(beta)
##                     [,1]
## AGE         4.490083e-02
## INTER_MARKS 7.806016e-04
## INCOME      1.426753e-05
## GPA_1       3.700375e-01

Chi_squared_test: Test of independence:

observed_values<-matrix(c(24,11,32,10,83,62,121,26,17,28,34,44),nrow = 4)
observed_values
##      [,1] [,2] [,3]
## [1,]   24   83   17
## [2,]   11   62   28
## [3,]   32  121   34
## [4,]   10   26   44
row.names(observed_values)<-c('Music','Craftswork','Reading','Drams')
colnames(observed_values)<-c('Maths','Chemistry','Physics')
contigency_table<-observed_values
contigency_table
##            Maths Chemistry Physics
## Music         24        83      17
## Craftswork    11        62      28
## Reading       32       121      34
## Drams         10        26      44
#Hypothesis Formulation:
#Ho: Degrees and Hobbies are Independent
#H1: Degrees and Hobbies are associated

#Level_of_significance:
alpha<-0.05

#Test_Statistics:

row_Total<-rowSums(observed_values)
row_Total
##      Music Craftswork    Reading      Drams 
##        124        101        187         80
column_Total<-colSums(observed_values)
column_Total
##     Maths Chemistry   Physics 
##        77       292       123
Total_values<-sum(observed_values)
expected_values <-outer(row_Total,column_Total,'*') /Total_values
expected_values
##               Maths Chemistry Physics
## Music      19.40650  73.59350   31.00
## Craftswork 15.80691  59.94309   25.25
## Reading    29.26626 110.98374   46.75
## Drams      12.52033  47.47967   20.00
chi_square_test<-sum(((observed_values-expected_values)^2)/expected_values)
chi_square_test
## [1] 54.10532
#Critical_Region
#reject Ho if X_cal >=X(alpha,df)
df<-(nrow(contigency_table)-1)*(ncol(contigency_table)-1)
df
## [1] 6
qchisq(1-0.05,df)
## [1] 12.59159
#Reject Ho

#By using function
result<-chisq.test(contigency_table)
if (result$p.value<alpha)
{
  cat("Reject Ho")
 }else  
   {cat("Do not Reject Ho")}
## Reject Ho
#Result:
#Reject Ho as p-value is less than alpha