Teodora V

Task 1

data()
data(package = .packages(all.available = TRUE))
#install.packages("carData")
library(carData)
#install.packages("utils")
library(utils)

mydata <- force(Blackmore)
head(mydata)
##   subject   age exercise   group
## 1     100  8.00     2.71 patient
## 2     100 10.00     1.94 patient
## 3     100 12.00     2.36 patient
## 4     100 14.00     1.54 patient
## 5     100 15.92     8.63 patient
## 6     101  8.00     0.14 patient

Explanation of dataset:

-Subject: This number represents a factor that goes with subject id codes. There are several observations for each subject, but because the girls were hospitalized at different ages, the number of cases and the age at the last case vary.

-Age: Subject’s age in years at the time of observation; all but the last observation for each subject were collected retrospectively at intervals of two years, starting at age 8.

-Exercise: This number represents the amount of exercise in which the subject engaged, expressed as estimated hours per week.

-Group:This variable is represented by factor with levels: control, Control subjects; patient, Eating-disordered patients.

summary(mydata)
##     subject         age           exercise          group    
##  100    :  5   Min.   : 8.00   Min.   : 0.000   control:359  
##  101    :  5   1st Qu.:10.00   1st Qu.: 0.400   patient:586  
##  105    :  5   Median :12.00   Median : 1.330                
##  106    :  5   Mean   :11.44   Mean   : 2.531                
##  107    :  5   3rd Qu.:14.00   3rd Qu.: 3.040                
##  108    :  5   Max.   :17.92   Max.   :29.960                
##  (Other):915
colnames(mydata) <- c("Subject", "Age","Exercise", "Group")
head(mydata)
##   Subject   Age Exercise   Group
## 1     100  8.00     2.71 patient
## 2     100 10.00     1.94 patient
## 3     100 12.00     2.36 patient
## 4     100 14.00     1.54 patient
## 5     100 15.92     8.63 patient
## 6     101  8.00     0.14 patient
colnames(mydata)[1] <- "Subject factor"
head(mydata)
##   Subject factor   Age Exercise   Group
## 1            100  8.00     2.71 patient
## 2            100 10.00     1.94 patient
## 3            100 12.00     2.36 patient
## 4            100 14.00     1.54 patient
## 5            100 15.92     8.63 patient
## 6            101  8.00     0.14 patient

Because of further analysis, we will create a new dataset eliminating the subject factor because we won’t be using this element.

mydata2 <- mydata [  , -1]
head(mydata2)
##     Age Exercise   Group
## 1  8.00     2.71 patient
## 2 10.00     1.94 patient
## 3 12.00     2.36 patient
## 4 14.00     1.54 patient
## 5 15.92     8.63 patient
## 6  8.00     0.14 patient
summary(mydata2)
##       Age           Exercise          Group    
##  Min.   : 8.00   Min.   : 0.000   control:359  
##  1st Qu.:10.00   1st Qu.: 0.400   patient:586  
##  Median :12.00   Median : 1.330                
##  Mean   :11.44   Mean   : 2.531                
##  3rd Qu.:14.00   3rd Qu.: 3.040                
##  Max.   :17.92   Max.   :29.960

Explanation of the results:

-1st Qu.:10.00 - 25% of the girls who participated in this study are 10 years old or younger, and 75% of them are older than 10.

-The range in which the age of participants in this study varies is from 8 to 17.92. The range is 9.92 years.

-Max. :29.960 - The maximum amount of exercise in which the subject engaged, expressed as estimated hours per week is 29.960 h/week.

-The interquartile range for age is 4 years.

-The interquartile range for the amount of exercise is 3.039,6 h/week.

-The average age of the girls in this study is 11.44 years.

-The average amount of exercise the girls in this study have per week is 2.531 hours.

-All data is available, but if there would be some values missing, we would delete those observations this way: install.packages(“tidyr”) library(tidyr) mydata3 <- drop_na(mydata2)

sd(mydata$Age)
## [1] 2.765609

This number 2.7656, represents an “average distance” (in years) between individual data points and the mean (average) of this dataset whitch is 11.44 years.

#install.packages("psych")
library(psych)
describe(mydata[ , c(-1, -4)])
##          vars   n  mean   sd median trimmed  mad min   max range skew
## Age         1 945 11.44 2.77  12.00   11.25 2.97   8 17.92  9.92 0.34
## Exercise    2 945  2.53 3.50   1.33    1.79 1.63   0 29.96 29.96 2.87
##          kurtosis   se
## Age         -0.98 0.09
## Exercise    11.13 0.11

Skewness of age and exercise is asymmetrical to the right.

#install.packages("pastecs")
library(pastecs)

round (stat.desc(mydata[ , c(-1,-4)]), 2)
##                   Age Exercise
## nbr.val        945.00   945.00
## nbr.null         0.00   112.00
## nbr.na           0.00     0.00
## min              8.00     0.00
## max             17.92    29.96
## range            9.92    29.96
## sum          10812.37  2391.46
## median          12.00     1.33
## mean            11.44     2.53
## SE.mean          0.09     0.11
## CI.mean.0.95     0.18     0.22
## var              7.65    12.22
## std.dev          2.77     3.50
## coef.var         0.24     1.38
hist(mydata$Exercise,
     main = "The amount of exercise",
     xlab = "Hour per week",
     ylab = "Number of girls",
     breaks = seq(from = 0, to= 30, by = 1))

Task 2

library(readxl)
massdata <- readxl::read_xlsx("~/BootCampTea/R Take Home Exam Tea/Body mass.xlsx")
massdata <- as.data.frame(massdata)
head(massdata)
##   ID Mass
## 1  1 62.1
## 2  2 64.5
## 3  3 56.5
## 4  4 53.4
## 5  5 61.3
## 6  6 62.2
library(psych)
describeBy(massdata$Mass)
## Warning in describeBy(massdata$Mass): no grouping variable requested
##    vars  n  mean   sd median trimmed  mad  min  max range skew
## X1    1 50 62.88 6.01   62.8   62.56 3.34 49.7 83.2  33.5 0.85
##    kurtosis   se
## X1     2.11 0.85

Minimum weight among 50 randomly selected ninth graders is 49.7kg, and maximum is 83.2kg. mean 62.88 - Average weight of 50 randomly selected ninth graders. median 62.8 - half of the kids weigh less than 62.8kg, and half of them skewness 0.85 - slightly to the right

Average weight of 50 randomly selected ninth graders in 2021/2022 school year is 62.88, which is 3.38kg more than the average weight in school year 2018/2019. This is the effect of online schooling.

summary(massdata[ , -1])
##    Min. 1st Qu.  Median    Mean 3rd Qu.    Max. 
##   49.70   60.23   62.80   62.88   64.50   83.20

1st Qu.:60.23 - 25% of the kids who participated in this study are 60.23kg or lighter, and 75% of them are heavier than 60.23kg.

hist(massdata$Mass, 
     main = "Distribution of the weight among kids",
     xlab = "Weight",
     ylab = "Number of kids",
     breaks = seq(from = 40, to= 90, by = 5))

Weight among kids is normally distributed, and most of them weigh between 60kg and 65kg (mode).

H0: Mu = 59.5 H1: Mu =/ 59.5

t.test(massdata$Mass,
       mu = 59.5,
       alternative = "two.sided")
## 
##  One Sample t-test
## 
## data:  massdata$Mass
## t = 3.9711, df = 49, p-value = 0.000234
## alternative hypothesis: true mean is not equal to 59.5
## 95 percent confidence interval:
##  61.16758 64.58442
## sample estimates:
## mean of x 
##    62.876

We compare the p-value to alpha (0.05) p-value: 0.000234

Because p-value is less than 5% (less than 0.001), we reject null hypothesis and except the H1 (alternative one)

The average weight increased to 62.876.

95 percent confidence interval for aritmetic mean: 61.16758 < mu < 64.58442, and based on this we would also reject H0, because 59.5 is not included in this interval.

#install.packages("effectsize")
library(effectsize)
## 
## Attaching package: 'effectsize'
## The following object is masked from 'package:psych':
## 
##     phi
cohens_d(massdata$Mass, mu =59.5)
## Cohen's d |       95% CI
## ------------------------
## 0.56      | [0.26, 0.86]
## 
## - Deviation from a difference of 59.5.

Standardized measure of the effect size is 0.56

interpret_cohens_d(0.56, rules = "sawilowsky2009")
## [1] "medium"
## (Rules: sawilowsky2009)

The increase in average weight among eighth graders was medium.

Task 3

library(readxl)
apt.data <- read_xlsx("./Apartments.xlsx")
head(apt.data)
## # A tibble: 6 × 5
##     Age Distance Price Parking Balcony
##   <dbl>    <dbl> <dbl>   <dbl>   <dbl>
## 1     7       28  1640       0       1
## 2    18        1  2800       1       0
## 3     7       28  1660       0       0
## 4    28       29  1850       0       1
## 5    18       18  1640       1       1
## 6    28       12  1770       0       1
apt.data <- as.data.frame(apt.data)
head(apt.data)
##   Age Distance Price Parking Balcony
## 1   7       28  1640       0       1
## 2  18        1  2800       1       0
## 3   7       28  1660       0       0
## 4  28       29  1850       0       1
## 5  18       18  1640       1       1
## 6  28       12  1770       0       1

Description:

apt.data$Parking <- factor(apt.data$Parking,
                            levels = c(0, 1), 
                            labels = c("No", "Yes"))
head(apt.data)
##   Age Distance Price Parking Balcony
## 1   7       28  1640      No       1
## 2  18        1  2800     Yes       0
## 3   7       28  1660      No       0
## 4  28       29  1850      No       1
## 5  18       18  1640     Yes       1
## 6  28       12  1770      No       1
apt.data$Balcony <- factor(apt.data$Balcony,
                            levels = c(0, 1), 
                            labels = c("No", "Yes"))
head(apt.data)
##   Age Distance Price Parking Balcony
## 1   7       28  1640      No     Yes
## 2  18        1  2800     Yes      No
## 3   7       28  1660      No      No
## 4  28       29  1850      No     Yes
## 5  18       18  1640     Yes     Yes
## 6  28       12  1770      No     Yes

H0: Mu = 1900 H1: Mu =/ 1900

t.test(apt.data$Price,
       mu = 1900,
       alternative = "two.sided")
## 
##  One Sample t-test
## 
## data:  apt.data$Price
## t = 2.9022, df = 84, p-value = 0.004731
## alternative hypothesis: true mean is not equal to 1900
## 95 percent confidence interval:
##  1937.443 2100.440
## sample estimates:
## mean of x 
##  2018.941

We compare the p-value to alpha (0.05)

p-value: 0.004731

Because p-value is less than 5%, we reject null hypothesis and except the H1 (alternative one)

The average price increased to 2018.941eur.

95 percent confidence interval for aritmetic mean: 1937.443 < mu < 2100.440, and based on this we would also reject H0, because 1900 is not included in this interval.

fit1 <- lm(Price ~ Age,
          data = apt.data)

summary(fit1)
## 
## Call:
## lm(formula = Price ~ Age, data = apt.data)
## 
## Residuals:
##    Min     1Q Median     3Q    Max 
## -623.9 -278.0  -69.8  243.5  776.1 
## 
## Coefficients:
##             Estimate Std. Error t value Pr(>|t|)    
## (Intercept) 2185.455     87.043  25.108   <2e-16 ***
## Age           -8.975      4.164  -2.156    0.034 *  
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## Residual standard error: 369.9 on 83 degrees of freedom
## Multiple R-squared:  0.05302,    Adjusted R-squared:  0.04161 
## F-statistic: 4.647 on 1 and 83 DF,  p-value: 0.03401

Price = 2185.445 - 8.975 Age If Age increases by 1 year, the price decreases by 8.975 on average. R-squared: 0.05302 - The coefficient of determination is showing how much variability of the dependent variable is explained by the effect of the explanatory variable. 5.3% of the variability of price can be explained by the effect of the age of the apartment.

cor(apt.data$Price, apt.data$Age)
## [1] -0.230255

Pearson Correlation Coefficient is showing that there is negative correlation, but it is not strong.

library(car)
## 
## Attaching package: 'car'
## The following object is masked from 'package:psych':
## 
##     logit
scatterplot(y = apt.data$Price, 
            x = apt.data$Age, 
            ylab = "Price per m2", 
            xlab = "Age of an apartment in years", 
            smooth = FALSE,
            boxplots = FALSE,
            regLine = TRUE)

There is negative correlation between age of an apartment and price per m2.

#install.packages("car")
library(car)
#install.packages("ggplot2")
library(ggplot2)
## 
## Attaching package: 'ggplot2'
## The following objects are masked from 'package:psych':
## 
##     %+%, alpha
#install.packages("reshape2")
library(reshape2)
library(car)
scatterplotMatrix(apt.data[ , c(-4,-5)],
                  smooth = FALSE)

library(Hmisc)
## 
## Attaching package: 'Hmisc'
## The following object is masked from 'package:psych':
## 
##     describe
## The following objects are masked from 'package:base':
## 
##     format.pval, units
rcorr(as.matrix(apt.data[ , c(-4,-5)])) 
##            Age Distance Price
## Age       1.00     0.04 -0.23
## Distance  0.04     1.00 -0.63
## Price    -0.23    -0.63  1.00
## 
## n= 85 
## 
## 
## P
##          Age    Distance Price 
## Age             0.6966   0.0340
## Distance 0.6966          0.0000
## Price    0.0340 0.0000

There is a very week linear relation between age and distance, and as previously shown, there is a weak, linear, negative relation between age and price.

Distance from the city center and price are semi strong negative correlated

fit2 <- lm(Price ~ Distance + Age + Parking + Balcony,
           data = apt.data)
summary(fit2)
## 
## Call:
## lm(formula = Price ~ Distance + Age + Parking + Balcony, data = apt.data)
## 
## Residuals:
##     Min      1Q  Median      3Q     Max 
## -459.92 -200.66  -57.48  260.08  594.37 
## 
## Coefficients:
##             Estimate Std. Error t value Pr(>|t|)    
## (Intercept) 2301.667     94.271  24.415  < 2e-16 ***
## Distance     -18.045      2.758  -6.543 5.28e-09 ***
## Age           -6.799      3.110  -2.186  0.03172 *  
## ParkingYes   196.168     62.868   3.120  0.00251 ** 
## BalconyYes     1.935     60.014   0.032  0.97436    
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## Residual standard error: 273.7 on 80 degrees of freedom
## Multiple R-squared:  0.5004, Adjusted R-squared:  0.4754 
## F-statistic: 20.03 on 4 and 80 DF,  p-value: 1.849e-11
vif(fit2)
## Distance      Age  Parking  Balcony 
## 1.104263 1.019308 1.121335 1.004865
mean(vif(fit2))
## [1] 1.062443

One is the lowest possible number, and they are all under five so there is no problem with our data. And there is no strong multicolinearity.

apt.data$StdResid <- round(rstandard(fit2), 3)
apt.data$CooksD <- round(cooks.distance(fit2), 3)
hist(apt.data$StdResid, 
     xlab = "Standardized residuals", 
     ylab = "Frequency", 
     main = "Histogram of standardized residuals")

shapiro.test(apt.data$StdResid)
## 
##  Shapiro-Wilk normality test
## 
## data:  apt.data$StdResid
## W = 0.95751, p-value = 0.006895

H0: Variable IS normally distributed H1: Variable is NOT normally distributed

We can reject null hypothesis becouse p value <<<5% —> We can say that standardizes residuals are not normally distributed.

apt.data$StdFitted <- scale(fit2$fitted.values) #Scale means standardization

library(car)
scatterplot(y = apt.data$StdResid, x = apt.data$StdFitted,
            ylab = "Standardized residuals",
            xlab = "Standardized fitted values",
            boxplots = FALSE,
            regLine = FALSE,
            smooth = FALSE)

library(olsrr)
## 
## Attaching package: 'olsrr'
## The following object is masked from 'package:datasets':
## 
##     rivers
ols_test_breusch_pagan(fit2)
## 
##  Breusch Pagan Test for Heteroskedasticity
##  -----------------------------------------
##  Ho: the variance is constant            
##  Ha: the variance is not constant        
## 
##               Data                
##  ---------------------------------
##  Response : Price 
##  Variables: fitted values of Price 
## 
##         Test Summary         
##  ----------------------------
##  DF            =    1 
##  Chi2          =    2.624141 
##  Prob > Chi2   =    0.1052494

The P value is 10%, which means that we can not reject H0. H0 says that variance is constant, so we don’t have a problem with heteroskedasticity.

summary(fit2)
## 
## Call:
## lm(formula = Price ~ Distance + Age + Parking + Balcony, data = apt.data)
## 
## Residuals:
##     Min      1Q  Median      3Q     Max 
## -459.92 -200.66  -57.48  260.08  594.37 
## 
## Coefficients:
##             Estimate Std. Error t value Pr(>|t|)    
## (Intercept) 2301.667     94.271  24.415  < 2e-16 ***
## Distance     -18.045      2.758  -6.543 5.28e-09 ***
## Age           -6.799      3.110  -2.186  0.03172 *  
## ParkingYes   196.168     62.868   3.120  0.00251 ** 
## BalconyYes     1.935     60.014   0.032  0.97436    
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## Residual standard error: 273.7 on 80 degrees of freedom
## Multiple R-squared:  0.5004, Adjusted R-squared:  0.4754 
## F-statistic: 20.03 on 4 and 80 DF,  p-value: 1.849e-11