Take home exam

Ivana Milivojevic

Task 1

#data()
#data(package = .packages(all.available = TRUE))
#install.packages("carData")
library(carData)
mydata<- force(Vocab)
head(mydata)
##          year    sex education vocabulary
## 19740001 1974   Male        14          9
## 19740002 1974   Male        16          9
## 19740003 1974 Female        10          9
## 19740004 1974 Female        10          5
## 19740005 1974 Female        12          8
## 19740006 1974   Male        16          8

This table is made based on the information gathered in the U.S. General Social Surveys from year 1972 to 2016. Its observations are respondents from the survey.

The explanation of the dataset:

-Year: year of the survey

-Sex: sex of the respondent, Female or Male

-Education: Education, presented in years

-Vocabulary: Vocabulary test score- number correct on a 10-word test

Source of the information: National Opinion Research Center General Social Survey. GSS Cumulative Data file 1972-2016, downloaded from http://gss.norc.org/. References Fox, J. (2016) Applied Regression Analysis and Generalized Linear Models, Third Edition. Sage. Fox, J. and Weisberg, S. (2019) An R Companion to Applied Regression, Third Edition, Sage.

colnames(mydata)<- c("SurveyYear", "Gender", "YearsOfEducation", "VocabTestScore")

head(mydata)
##          SurveyYear Gender YearsOfEducation VocabTestScore
## 19740001       1974   Male               14              9
## 19740002       1974   Male               16              9
## 19740003       1974 Female               10              9
## 19740004       1974 Female               10              5
## 19740005       1974 Female               12              8
## 19740006       1974   Male               16              8

I was curious and I wanted to see the results from the first and the last 16 years of the surveys to see if there has been any specific change in the basic summary results regarding the fact that the educational systems and society has been through different changes from 1974 to 2016(42 years difference between the first and last survey). In order to make mydata01 and mydata1 where I could see the gender, test scores, years of education for the time period from 2000-2016 and 1974-1988,I filtered the data in next way:

 mydata01<- mydata[mydata$SurveyYear>=2000 & mydata$SurveyYear<2016, ] 
 mydata1 <-mydata[mydata$SurveyYear>=1974 & mydata$SurveyYear<1988, ]
 summary(mydata01) 
##    SurveyYear      Gender     YearsOfEducation VocabTestScore  
##  Min.   :2000   Female:5340   Min.   : 0.00    Min.   : 0.000  
##  1st Qu.:2004   Male  :4269   1st Qu.:12.00    1st Qu.: 5.000  
##  Median :2008                 Median :13.00    Median : 6.000  
##  Mean   :2008                 Mean   :13.56    Mean   : 6.042  
##  3rd Qu.:2012                 3rd Qu.:16.00    3rd Qu.: 7.000  
##  Max.   :2014                 Max.   :20.00    Max.   :10.000
 summary(mydata1)
##    SurveyYear      Gender     YearsOfEducation VocabTestScore  
##  Min.   :1974   Female:5194   Min.   : 0.00    Min.   : 0.000  
##  1st Qu.:1976   Male  :3953   1st Qu.:11.00    1st Qu.: 4.000  
##  Median :1982                 Median :12.00    Median : 6.000  
##  Mean   :1980                 Mean   :12.19    Mean   : 5.913  
##  3rd Qu.:1984                 3rd Qu.:14.00    3rd Qu.: 7.000  
##  Max.   :1987                 Max.   :20.00    Max.   :10.000

I can see that on average in first 16 years of surveying average years of education were 12.19 and in the last 16 years of surveying average years spent on education 13.56. The average test score is quite similar being 5.913 in the first 16 years of taking the survey and 6.042 for the last 16 years of survey. During this analysis I saw the gap in the year 1987 and 1988 which I checked in next step

hist(mydata$SurveyYear,
     main= "Years when survey took place",
     ylab = "Frequency",
     xlab = "Years",
     breaks = seq(1974,2016,1),
     right = FALSE)

Here I noticed the gaps in the years when survey took and did not took place. Bigger gaps are the 3 year gaps between 1979-1982 and the one between 2001-2004, which are more visible on the next histogram:

hist(mydata$SurveyYear,
     main= "Years when survey took place",
     ylab = "Frequency",
     xlab = "Years",
     right = FALSE)

Because of the gaps in the years and because I have seen that there were no significant changes between the results from first and last 16 years of surveying, First column is deleted and the other data is analysed.

mydata2<- mydata[ , -1] #deleted the first column
head(mydata2)
##          Gender YearsOfEducation VocabTestScore
## 19740001   Male               14              9
## 19740002   Male               16              9
## 19740003 Female               10              9
## 19740004 Female               10              5
## 19740005 Female               12              8
## 19740006   Male               16              8
summary(mydata2)
##     Gender      YearsOfEducation VocabTestScore  
##  Female:17148   Min.   : 0.00    Min.   : 0.000  
##  Male  :13203   1st Qu.:12.00    1st Qu.: 5.000  
##                 Median :12.00    Median : 6.000  
##                 Mean   :13.03    Mean   : 6.004  
##                 3rd Qu.:15.00    3rd Qu.: 7.000  
##                 Max.   :20.00    Max.   :10.000

Explanation of results:

For Gender: This survey had more females(17148) and less males (13203) participants.

For YearsOfEduacation:

mean:13.03 - average years spent on education for our population is 13.03

3rd Qu.:15.00 - 75% of the participants spent 15 years or less on education and 25% of people spent more than 15 years on education

20.00: maximal amount of time one spent on education is 20 years.

For VocabTestScore:

1st Qu.: 5.000 - 25% of participants had scored correct 5 words or less on 10-word question test and 75% of the participants had more than 5 correct answers on 10-word test.

Median : 6.000 - When participants scores are ordered from lowest to highest score on the 10-word test, the score number in the exact middle was 6.

Min. : 0.000 - the minimal score in the 10-word test was 0.

library(psych)
describeBy(mydata2, mydata2$Gender)  #here I have divided results for males and females to compare them. 
## 
##  Descriptive statistics by group 
## group: Female
##                  vars     n  mean   sd median trimmed  mad min max range  skew
## Gender*             1 17148  1.00 0.00      1    1.00 0.00   1   1     0   NaN
## YearsOfEducation    2 17148 12.92 2.92     12   12.97 2.97   0  20    20 -0.20
## VocabTestScore      3 17148  6.04 2.09      6    6.10 1.48   0  10    10 -0.25
##                  kurtosis   se
## Gender*               NaN 0.00
## YearsOfEducation     0.91 0.02
## VocabTestScore      -0.05 0.02
## ------------------------------------------------------------ 
## group: Male
##                  vars     n  mean   sd median trimmed  mad min max range  skew
## Gender*             1 13203  2.00 0.00      2    2.00 0.00   2   2     0   NaN
## YearsOfEducation    2 13203 13.18 3.20     13   13.25 2.97   0  20    20 -0.32
## VocabTestScore      3 13203  5.96 2.14      6    5.99 1.48   0  10    10 -0.17
##                  kurtosis   se
## Gender*               NaN 0.00
## YearsOfEducation     0.84 0.03
## VocabTestScore      -0.24 0.02

Comparing females (first data frame with n=17148) and males (second data frame with n=13203) we can see that average years of education for woman is 12.92 years with average vocabulary test score 6.04, for total number of observations and the average years of education of males is 13.18 years which is a bit higher than females and theirs average total score on 10-word Vocabulary test was 5.96 which overall indicates similar data.

In next step the data is presented via scatterplot.

library(car)
## 
## Attaching package: 'car'
## The following object is masked from 'package:psych':
## 
##     logit
scatterplot(mydata2$YearsOfEducation ~ mydata2$VocabTestScore,
            ylab = "Years of education",
            xlab = "Vocabulary test score",
            smooth = FALSE,
            boxplots = FALSE)

The linear regression line in this scatterplot shows us that more years of education one average person has, the better average score on the 10-word vocabulary test had. In other words if the year of education increased, the result on the 10-word vocabulary exam also increased.

Task 2

A researcher examined the effects of online schooling on body weight in ninth graders. Based on data from the 2018/2019 school year, the average weight was 59.5 kg. At the beginning of the 2021/2022 school year, researchers randomly selected 50 ninth graders and measured their weight.

The results are first added to the same folder as the rmd file is -where this homework is saved, than extracted in R and first 6 values are presented in the table bellow:

mydataT1 <- read.table("./Body mass.csv", 
                       header = TRUE, 
                       sep = ";", 
                       dec = "," )

head(mydataT1)
##   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(pastecs)
stat.desc(mydataT1)
##                       ID         Mass
## nbr.val        50.000000 5.000000e+01
## nbr.null        0.000000 0.000000e+00
## nbr.na          0.000000 0.000000e+00
## min             1.000000 4.970000e+01
## max            50.000000 8.320000e+01
## range          49.000000 3.350000e+01
## sum          1275.000000 3.143800e+03
## median         25.500000 6.280000e+01
## mean           25.500000 6.287600e+01
## SE.mean         2.061553 8.501407e-01
## CI.mean.0.95    4.142845 1.708422e+00
## var           212.500000 3.613696e+01
## std.dev        14.577380 6.011403e+00
## coef.var        0.571662 9.560727e-02
round(stat.desc(mydataT1$Mass), 1)
##      nbr.val     nbr.null       nbr.na          min          max        range 
##         50.0          0.0          0.0         49.7         83.2         33.5 
##          sum       median         mean      SE.mean CI.mean.0.95          var 
##       3143.8         62.8         62.9          0.9          1.7         36.1 
##      std.dev     coef.var 
##          6.0          0.1
summary(mydataT1$Mass)
##    Min. 1st Qu.  Median    Mean 3rd Qu.    Max. 
##   49.70   60.23   62.80   62.88   64.50   83.20

The heaviest ninth grader has 83.2kg and the lightest ninth grader had 49.7kg. The average weight of ninth grader for the year 2021/2022 was 62.8kg. That is 3.3kg greater value that the average weight of ninth graders from the measurement form year 2018/2019. In the year 2021/2022, 75% of the ninth graders had 64.5kg or less while the 25% of them had more than 64.5kg.

Distribution of the weight of ninth graders is presented with the histogram bellow:

library(ggplot2)
## 
## Attaching package: 'ggplot2'
## The following objects are masked from 'package:psych':
## 
##     %+%, alpha
ggplot(mydataT1, aes(x=Mass)) +
         geom_histogram(binwidth = 5, colour= "blue", fill= "red")+
         ylab("number of ninth graders")

mean(mydataT1$Mass)
## [1] 62.876
sd(mydataT1$Mass)
## [1] 6.011403
#Here I wanted to see the mean of new sample from 2021/2022 and standard deviation from it before testing the hypothesis (if did not change compared to the year 2018/2019) and to see if there is a bigger or smaller difference and possibility to overlap somewhere. 

With the visible difference in means I still tested the hypothesis:

H0: Mu= 59.5 H1: Mu=/ 59.5

t.test(mydataT1$Mass,
       mu= 59.5,
       alternative= "two.sided")
## 
##  One Sample t-test
## 
## data:  mydataT1$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

When I compare p-value which is 0.000234 to alfa (0.05) I can conclude that: I should reject H0 at p<0.001 and accept H1. Average weight of the ninth graders in the year 2021/2022 is different than the average weight of ninth graders in the year 2018/2019. Average weight of ninth graders increased.

95%confidence interval for the arithmetic mean: 61.16758 < Mu < 64.58442

I can also here see that the average weight of ninth graders from the 2018/2019 testing is not included in the confidence interval that is in results so I conclude that I will reject H0 at 5%.

down below I calculated the effect size:

library(psych)
library(effectsize)
## 
## Attaching package: 'effectsize'
## The following object is masked from 'package:psych':
## 
##     phi
cohens_d(mydataT1$Mass, mu=59.5)
## Cohen's d |       95% CI
## ------------------------
## 0.56      | [0.26, 0.86]
## 
## - Deviation from a difference of 59.5.
interpret_cohens_d(0.56, rules = "sawilowsky2009") #Here I checked how big is this change in difference 
## [1] "medium"
## (Rules: sawilowsky2009)

The increase in the weight can be explained as medium.

Task 3

Import the dataset Apartments.xlsx
library(readxl)
mydataT3<- read_xlsx("./Apartments.xlsx")
mydataT3<- as.data.frame(mydataT3)
head(mydataT3)
##   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:

  • Age: Age of an apartment in years

  • Distance: The distance from city center in km

  • Price: Price per m2

  • Parking: 0-No, 1-Yes

  • Balcony: 0-No, 1-Yes

Change categorical variables into factors.

mydataT3$ParkingFactor<- factor(mydataT3$Parking,
                                levels = c(0,1),
                                labels = c("No","Yes"))
mydataT3$BalconyFactor<- factor(mydataT3$Balcony,
                                levels = c(0,1),
                                labels = c("No","Yes"))
head(mydataT3, 5)
##   Age Distance Price Parking Balcony ParkingFactor BalconyFactor
## 1   7       28  1640       0       1            No           Yes
## 2  18        1  2800       1       0           Yes            No
## 3   7       28  1660       0       0            No            No
## 4  28       29  1850       0       1            No           Yes
## 5  18       18  1640       1       1           Yes           Yes

Test the hypothesis H0: Mu_Price = 1900 eur. What can you conclude?

t.test(mydataT3$Price,
       mu=1900,
       alternative = "two.sided")
## 
##  One Sample t-test
## 
## data:  mydataT3$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

The p value is 0.004 (less than 5%) so I can say that there is an evidence to reject H0 at p=0.004731 in favor of alternative hypothesis. With the 95% confidence I can reject H0 and conclude that the price is higher. Since the p value is quite close to 5% and lowest point in the confidence interval was 1937.443euro compared to the given price for the hypothesis (1900euro) we can also perform some additional examinations, for example to check the effect size:

library(effectsize)
cohens_d(mydataT3$Price, mu= 1900)
## Cohen's d |       95% CI
## ------------------------
## 0.31      | [0.10, 0.53]
## 
## - Deviation from a difference of 1900.
interpret_cohens_d(0.31, rules = "sawilowsky2009")
## [1] "small"
## (Rules: sawilowsky2009)

The increase in price is small, by Sawilowsky (2009).

Estimate the simple regression function: Price = f(Age). Save results in object fit1 and explain the estimate of regression coefficient, coefficient of correlation and coefficient of determination.

fit1<- lm(Price~Age,
         data = mydataT3)
summary(fit1)
## 
## Call:
## lm(formula = Price ~ Age, data = mydataT3)
## 
## 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

Regression constant is 2185.455 - in this case this is expected price for new apartment per m2.

Regression coefficient is -8.975

Price^=2185.455+(-8.975)Age

If Age increases by 1 year, than the price decreases by 8.975euro per m2 on average.

H0: Beta = 0

H1: Beta =/ 0

p= 0.034 (< 5%)

We reject H0 at p< 0.05

The age statistically affects price.

R-squared: 0.05302

R-squared represents the coefficient of determination and in this case we can say that just 5.3% of variability of price per m2 of apartments can be explained by the effect of age of the apartment in years.

cor(mydataT3$Price, mydataT3$Age)
## [1] -0.230255

Correlation coefficient is small so the relationship between variables is weak. Moreover it is negative correlation, which means that if one variable increases the other one tends to decrease. Hence, if the apartment age increases the price of the apartment per m2 tends to decrease, keeping in mind that in this case the correlation is just not very strong.

Show the scateerplot matrix between Price, Age and Distance. Based on the matrix determine if there is potential problem with multicolinearity.

scatterplotMatrix(mydataT3[ , c(-4,-5,-6,-7)],
                  smooth = FALSE)

Based on the matrix we can not see the significant problem with multicolinearity, (more heteroskedasticity), it is not definite since the data is not perfectly “scattered next to regression line”. With the price and distance we can see that the data is at one point of regression line quite close but it is not the case for the whole line, for other examples it is even more scattered.
Using the correlation matrix we can explain the pictures better.

library(psych)
library(base)
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(mydataT3[ , c(-4,-5,-6,-7)]))
##            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

We use the Pearson correlation coefficients to see how strong the correlation is between our variables (positive- one tends to increase when other increase, negative- one tends to decrease when the other increase):

0.0-0.1 - very weak

0.1-0.3 weak

0.3-0.7 semi strong

0.7-0.9 strong

0.9-1.0 very strong

There is very weak positive linear relationship between age of apartment and distance from the city.
There is weak negative linear relationship between price per m2 and age of apartment. There is semi strong negative linear relationship between price of the apartment per m2 and distance from the city.

Estimate the multiple regression function: Price = f(Age, Distance). Save it in object named fit2.

fit2<- lm(Price ~ Age + Distance,
          data = mydataT3)

Chech the multicolinearity with VIF statistics. Explain the findings.

vif(fit2)
##      Age Distance 
## 1.001845 1.001845
mean(vif(fit2))
## [1] 1.001845

Since both values(variance inflation factors VIF) are under 5 there is no need to remove any of them.There is no problem with strong multicolinearity with data.

Calculate standardized residuals and Cooks Distances for model fit2. Remove any potentially problematic units (outliers or units with high influence).

mydataT3$StdResiduals <- round(rstandard(fit2), 3)
mydataT3$CooksD <- round(cooks.distance(fit2), 3)

head(mydataT3)
##   Age Distance Price Parking Balcony ParkingFactor BalconyFactor StdResiduals
## 1   7       28  1640       0       1            No           Yes       -0.665
## 2  18        1  2800       1       0           Yes            No        1.783
## 3   7       28  1660       0       0            No            No       -0.594
## 4  28       29  1850       0       1            No           Yes        0.754
## 5  18       18  1640       1       1           Yes           Yes       -1.073
## 6  28       12  1770       0       1            No           Yes       -0.778
##   CooksD
## 1  0.007
## 2  0.030
## 3  0.006
## 4  0.008
## 5  0.005
## 6  0.005

Following the lectures and literature, the outlier is found when the value is higher than 3. In this case we have value that is higher than -2 (checked in mydataT3 table StandResiduals in descending order) but not higher than -3. Since we have large sample (>30) we do not need to do the Shapiro test because we can just assume that the Standardized residuals are normally distributed. For the cooks distance we can check the histogram,(based on the data from the mydataT3 table when in descending order there are one or two values that ar quite higher than the rest of it) I hope that this histogram will help me decide what is the one with high influence.

hist(mydataT3$CooksD,
     xlab = "Cooks distance",
     ylab = "Frequency",
     main = "Histogram of Cooks Distance")

Here I can see that one units is possible influential case. Here are presented the fist 6 units:

head(mydataT3[order(-mydataT3$CooksD),],6) 
##    Age Distance Price Parking Balcony ParkingFactor BalconyFactor StdResiduals
## 38   5       45  2180       1       1           Yes           Yes        2.577
## 55  43       37  1740       0       0            No            No        1.445
## 33   2       11  2790       1       0           Yes            No        2.051
## 53   7        2  1760       0       1            No           Yes       -2.152
## 22  37        3  2540       1       1           Yes           Yes        1.576
## 39  40        2  2400       0       1            No           Yes        1.091
##    CooksD
## 38  0.320
## 55  0.104
## 33  0.069
## 53  0.066
## 22  0.061
## 39  0.038

I can see that number 38 is quite different form the other samples so I will remove it. Since the sample I have is not very large I will not remove any other second one because i would risk loosing some other important data for analysis.

mydataT3<-mydataT3[-38, ]

Now I can run the function again and check the statistics

fit2<-lm (Price ~ Age + Distance,
          data= mydataT3)

mydataT3$StdResiduals<- round(rstandard(fit2), 3)
mydataT3$CooksD<- round(cooks.distance(fit2), 3) 

hist(mydataT3$StdResiduals,
      xlab = "Standardized residuals", 
     ylab = "Frequency", 
     main = "Histogram of standardized residuals")

shapiro.test(mydataT3$StdResiduals)
## 
##  Shapiro-Wilk normality test
## 
## data:  mydataT3$StdResiduals
## W = 0.95649, p-value = 0.006355
hist(mydataT3$CooksD,
      xlab = "Cooks distance", 
     ylab = "Frequency", 
     main = "Histogram of Cooks distances")

I checked the code once even without the 55th case (just added -55 in the part of the code where I removed 38th) but it kept making new influential cases here so I returned to this one because I would loose too much data if I removed them all.

Check for potential heteroskedasticity with scatterplot between standarized residuals and standrdized fitted values. Explain the findings.

mydataT3$StdFitted <- scale(fit2$fitted.values)

Here I have created the set of data with standardized (used the function SCALE for standardization of values) fitted values from f2 and saved it in mydataT3.

library(car)
scatterplot(y=mydataT3$StdResiduals, x=mydataT3$StdFitted,
            ylab = "Standardized residuals",
            xlab = "Standardized fitted values",
            boxplots = FALSE,
            regLine = FALSE,
            smooth = FALSE)

library(ggplot2)
ggplot(mydataT3, aes(y=StdResiduals, x=StdFitted)) +
  geom_point() +
  ylab("standardized residuals")

  xlab("Standardized fitted values")
## $x
## [1] "Standardized fitted values"
## 
## attr(,"class")
## [1] "labels"

Since it is not 100% secure to determine heteroskedasticity only by picture, I used the Breusch-Pagan test from more information:

library(datasets)
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.927455 
##  Prob > Chi2   =    0.08708469

H0 = homoskedasticity

H1 = heteroskedasticity

Based on the p value we cannot reject the H0 because the p>0.05 Since the results of the test says that the variance is constant than we do not have a problem with heteroskedasticity.

Are standardized residuals ditributed normally? Show the graph and formally test it. Explain the findings.

shapiro.test(mydataT3$StdResiduals)
## 
##  Shapiro-Wilk normality test
## 
## data:  mydataT3$StdResiduals
## W = 0.95649, p-value = 0.006355
hist(mydataT3$StdResiduals, 
     xlab = "Standardized residuals", 
     ylab = "Frequency", 
     main = "Histogram of standardized residuals")

H0: variable is normally distributed

H1: Variable is not normally distributed

Since the p-value = 0.006355, at Shapiro-Wilk normality test, is lower than 5% we can conclude that the we can reject the null hypothesis. In this case that means that given values are not normally distributed but since we have a large sample (larger than 30) it is safe to assume that the distribution will be normal.

Estimate the fit2 again without potentially excluded units and show the summary of the model. Explain all coefficients.

summary(fit2)
## 
## Call:
## lm(formula = Price ~ Age + Distance, data = mydataT3)
## 
## Residuals:
##     Min      1Q  Median      3Q     Max 
## -604.92 -229.63  -56.49  192.97  599.35 
## 
## Coefficients:
##             Estimate Std. Error t value Pr(>|t|)    
## (Intercept) 2456.076     73.931  33.221  < 2e-16 ***
## Age           -6.464      3.159  -2.046    0.044 *  
## Distance     -22.955      2.786  -8.240 2.52e-12 ***
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## Residual standard error: 276.1 on 81 degrees of freedom
## Multiple R-squared:  0.4838, Adjusted R-squared:  0.4711 
## F-statistic: 37.96 on 2 and 81 DF,  p-value: 2.339e-12

Both distance and age affect the price given the p values (both p values are lower than 5%).

Explanation of b1:

My regression coefficient for the age is now -6,464 which means that if apartment age is increased by 1 year, than the price decreases by 6.464euro on average per m2 (p<0.05), assuming that all other explanatory variables, included in the model, are constant.

Explanation of b2:

The regression coefficient for the distance is -22.955 which means that if the distance of the apartment from the city center is increased by 1km, than the average price of that apartment decreases by 22.955euro per m2 on average (p<0.001), assuming that all other explanatory variables, included in the model, are constant.

Multiple R-squared: 0.4838

We can say that 48.38% of the variability of price of the apartment per m2 can be explained by the linear effect of age of the apartment and distance from city center.

For the correlation coefficient we use the Pearson correlation coefficients to see how strong is the correlation between variables.

rcorr(as.matrix(mydataT3[ , c(-4,-5,-6,-7,-8,-9,-10)]))
##            Age Distance Price
## Age       1.00     0.09 -0.23
## Distance  0.09     1.00 -0.68
## Price    -0.23    -0.68  1.00
## 
## n= 84 
## 
## 
## P
##          Age    Distance Price 
## Age             0.3963   0.0387
## Distance 0.3963          0.0000
## Price    0.0387 0.0000

The linear relationship between the price and age is the same as first counted, the linear relationship between the distance and age has been changed from 0.04 to 0.09 which is still weak positive correlation. The linear relationship between the price and distance has been changed from -0.63 to -0.68 but still remains the semi strong negative linear relationship. I can conclude that after the changes in variables the new correlation coefficients increased (except for price and age which remained the same) showing the slightly stronger correlations between the variables.

The coefficient of multiple correlations is:

sqrt(summary(fit2)$r.squared)
## [1] 0.6955609

There is a semi strong linear relationship between price and both explanatory variables (age and distance) which are included in the model.

Estimate the linear regression function Price = f(Age, Distance, Parking and Balcony). Be careful to correctly include categorical variables. Save the object named fit3.

fit3 <-lm(Price~ Age+ Distance+ ParkingFactor+ BalconyFactor,
          data= mydataT3)

With function anova check if model fit3 fits data better than model fit2.

anova(fit2,fit3)
## Analysis of Variance Table
## 
## Model 1: Price ~ Age + Distance
## Model 2: Price ~ Age + Distance + ParkingFactor + BalconyFactor
##   Res.Df     RSS Df Sum of Sq      F  Pr(>F)  
## 1     81 6176767                              
## 2     79 5654480  2    522287 3.6485 0.03051 *
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

H0: model 1(fit2) is better

H2: model 2 (fit3) is better

p<0.05

The H0 is rejected at p<0.05. Model 2 is better because it explains more variability in our analysis of the price (because it has the additional variables of PrakingFactor and BalconyFactor that help better explanation of the Price).

Show the results of fit3 and explain regression coefficient for both categorical variables. Can you write down the hypothesis which is being tested with F-statistics, shown at the bottom of the output?

summary(fit3)
## 
## Call:
## lm(formula = Price ~ Age + Distance + ParkingFactor + BalconyFactor, 
##     data = mydataT3)
## 
## Residuals:
##     Min      1Q  Median      3Q     Max 
## -473.21 -192.37  -28.89  204.17  558.77 
## 
## Coefficients:
##                  Estimate Std. Error t value Pr(>|t|)    
## (Intercept)      2329.724     93.066  25.033  < 2e-16 ***
## Age                -5.821      3.074  -1.894  0.06190 .  
## Distance          -20.279      2.886  -7.026 6.66e-10 ***
## ParkingFactorYes  167.531     62.864   2.665  0.00933 ** 
## BalconyFactorYes  -15.207     59.201  -0.257  0.79795    
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## Residual standard error: 267.5 on 79 degrees of freedom
## Multiple R-squared:  0.5275, Adjusted R-squared:  0.5035 
## F-statistic: 22.04 on 4 and 79 DF,  p-value: 3.018e-12

Balcony (b4):

Observing the P values, I cannot say that Balcony has statistical effect on the price.

Parking (b3)

H0: Beta3 = 0

H1: Beta3 =/ 0

p=0.009

p<0.01

Explanation of b3= If the parking is available with the apartment the price increases by 167.531euro on average (p<0.01) compared to the apartments that do not have the parking and assuming that all other explanatory variables, included in the model, are constant.

The R factor also increased a bit compared to the previous model and now more than 50% of the price (52.75%)is explained by the variables: Age of the apartment, Distance from the city center, availability of the Parking and availability of Balcony.

Observing F statistics

F-statistic: 22.04 on 4 and 79 DF, p-value: 3.018e-12

H0= Age,Distance, ParkingFactor, BalconyFactor does not have significant effect on Price

H1= Age,Distance, ParkingFactor, BalconyFactor have significant impact on the Price

With p-value<0.001 (on the F-test:22.04 on 4 and 79 DF) I can reject the H0 and conclude that at least one of my variables has statistical/significant impact on the Price.

Save fitted values and claculate the residual for apartment ID2.

mydataT3$Fitted<- fitted.values(fit3)
mydataT3$Residuals<- residuals(fit3)

head(mydataT3[colnames(mydataT3) %in% c("Price", "Fitted", "Residuals")])
##   Price   Fitted  Residuals
## 1  1640 1705.952  -65.95206
## 2  2800 2372.197  427.80292
## 3  1660 1721.159  -61.15894
## 4  1850 1563.431  286.56890
## 5  1640 2012.244 -372.24396
## 6  1770 1908.177 -138.17733

For the apartment ID2 the residual is 427.80292euro.

That means that the actual price is 2800euro and that one that it was predicted by the model I have estimated is 2372.2euro.

e = Y - Y(fitted)

The residuals are calculated by subtraction of estimate (Y(fitted)) from actual value (Y). Hence, by the 427.8euro is my price below the actual price value.