Task 1

1.1 Explain the data set (the variables used in the analysis).

mydata <- read.table("./Personal_finances.csv", header=TRUE, sep=",", dec=".")
head(mydata) #Showing first 6 units
##       Date Account      Category  Amount Currency   Description
## 1 8/1/2022       1         House -185.00        $       Monitor
## 2 8/1/2022       1    Eating out      NA      EUR         Glovo
## 3 8/2/2022       1 Entertainment   -7.00      EUR  Pijaca mesto
## 4 8/3/2022       1    Eating out   -4.18      EUR         Glovo
## 5 8/5/2022       1 Entertainment   -5.00      EUR Pijaca tennis
## 6 8/6/2022       1         Gifts  -20.00      EUR Darilo Kodela

For Task 1, I used data on my personal finances. For about a year
and a half, I have been recording all my income and expenses in the mobile app
Monefy(https://apps.apple.com/us/app/monefy-money-tracker/id1212024409).
In this analysis, I used data from interval 1. 8. 2022 - 1. 8. 2023.

Descriptions:
- Date: date of transaction
- Account: 0 - cash, 1 - card
- Category: Category in which the transaction was made
- Amount: Transaction amunt. A negative value represents an outflow and positive value an inflow
- Currency: Values can be in Euros(EUR) or Dolars($)
- Description: Short description of transaction

1.2 Perform some data manipulations

1.2.1 Change categorical values to factors

mydata$AccountF <- factor(mydata$Account,
                        levels = c (1, 2),
                        labels = c ("Card", "Cash")) # 
head(mydata)
##       Date Account      Category  Amount Currency   Description AccountF
## 1 8/1/2022       1         House -185.00        $       Monitor     Card
## 2 8/1/2022       1    Eating out      NA      EUR         Glovo     Card
## 3 8/2/2022       1 Entertainment   -7.00      EUR  Pijaca mesto     Card
## 4 8/3/2022       1    Eating out   -4.18      EUR         Glovo     Card
## 5 8/5/2022       1 Entertainment   -5.00      EUR Pijaca tennis     Card
## 6 8/6/2022       1         Gifts  -20.00      EUR Darilo Kodela     Card

1.2.2 Convert amounts in $ to EUR

Data set included some amounts in dollars so we had to covert them to EUR.

suppressPackageStartupMessages(library(dplyr)) # to exclude package attachment messages in knit
mydata <- mydata %>%
  mutate(
    Amount = ifelse(Currency == "$", Amount / 1.07, round(Amount, 2)),
    Currency = ifelse(Currency == "$", "EUR", Currency)
  )

head(mydata)
##       Date Account      Category    Amount Currency   Description AccountF
## 1 8/1/2022       1         House -172.8972      EUR       Monitor     Card
## 2 8/1/2022       1    Eating out        NA      EUR         Glovo     Card
## 3 8/2/2022       1 Entertainment   -7.0000      EUR  Pijaca mesto     Card
## 4 8/3/2022       1    Eating out   -4.1800      EUR         Glovo     Card
## 5 8/5/2022       1 Entertainment   -5.0000      EUR Pijaca tennis     Card
## 6 8/6/2022       1         Gifts  -20.0000      EUR Darilo Kodela     Card

1.2.3 Remove rows with non-available amounts

filtered_data <- mydata %>%
  filter(!is.na(Amount))
head(filtered_data)
##       Date Account      Category    Amount Currency   Description AccountF
## 1 8/1/2022       1         House -172.8972      EUR       Monitor     Card
## 2 8/2/2022       1 Entertainment   -7.0000      EUR  Pijaca mesto     Card
## 3 8/3/2022       1    Eating out   -4.1800      EUR         Glovo     Card
## 4 8/5/2022       1 Entertainment   -5.0000      EUR Pijaca tennis     Card
## 5 8/6/2022       1         Gifts  -20.0000      EUR Darilo Kodela     Card
## 6 8/6/2022       1    Eating out  -25.0000      EUR Kosilo gurman     Card

1.3 Present the descriptive statistics for your variables and explain at least 3 different sample statistics (mean, median, etc.)

I was interested in statistics on how much money I spent on eating out in restaurants and ordering
food delivery (both categories fall under ‘Eating out’).

eating_out_amounts <- subset(filtered_data, Category == "Eating out")$Amount
eating_out_amounts <- eating_out_amounts * -1 # multiply by -1, because spending is negative values
summary(eating_out_amounts)
##    Min. 1st Qu.  Median    Mean 3rd Qu.    Max. 
##   0.400   3.828   5.115   6.999   8.390  50.500
length(eating_out_amounts)
## [1] 238

From the descriptive statistics we can see:

Mean: The average meal I ate out last year cost me €7.29.
Max: The most expensive meal in the last year cost me 50.5 EUR.
1st Qu: 75% of meals I ate in the restaurants/glovo in last year costs me more than 4.17 EUR.
Number of meals: I have eaten out 257 times in the last year.

hist(eating_out_amounts,
    xlab = "Price", 
     ylab = "Frequency", 
     main = "Histogram of my eating out spendings")

We can see from the histogram that majority of my meals costed less than 10 EUR, this is mainly due to
the use of student bones.

1.4 Graph the distribution of the variables using histograms, scatterplots, and/or boxplots. Explain the findings.

I was interested in how money is spent on a monthly basis. Therefore, I aggregated the
time series data into monthly intervals and displayed the values for total monthly expenditures,
monthly expenditures for eating out and monthly expenditure for entertainment.

# Convert the 'Date' column to Date type
filtered_data$Date <- as.Date(filtered_data$Date, format = "%m/%d/%Y")

# Create new columns for Month and Year
filtered_data <- filtered_data %>%
  mutate(Month = format(Date, "%Y-%m"),
         Year = format(Date, "%Y"))

# Group by Year and Month and calculate the total_sum, sum for Entertainment and Eating out categories
spendings <- filtered_data %>%
  group_by(Year, Month) %>%
  summarize(
    total_sum = sum(ifelse(Amount < 0, Amount, 0)),
    Entertainment_sum = sum(ifelse(Category == "Entertainment" & Amount < 0, Amount, 0)),
    Eating_out_sum = sum(ifelse(Category == "Eating out" & Amount < 0, Amount, 0))
  )
## `summarise()` has grouped output by 'Year'. You can override using the
## `.groups` argument.
print(spendings)
## # A tibble: 12 × 5
## # Groups:   Year [2]
##    Year  Month   total_sum Entertainment_sum Eating_out_sum
##    <chr> <chr>       <dbl>             <dbl>          <dbl>
##  1 2022  2022-08     -377.            -113            -67.1
##  2 2022  2022-09     -488.            -385            -35.6
##  3 2022  2022-10    -1059.            -154.          -101. 
##  4 2022  2022-11     -494.            -114.          -130. 
##  5 2022  2022-12    -1498.            -946           -215. 
##  6 2023  2023-01     -253.             -10.5         -174. 
##  7 2023  2023-02     -720.            -316.          -110. 
##  8 2023  2023-03     -523.            -194.          -115. 
##  9 2023  2023-04    -1075.            -778.           -69.0
## 10 2023  2023-05     -747.             -45           -306. 
## 11 2023  2023-06     -456.            -120.          -131. 
## 12 2023  2023-07     -562.             -84           -212.
# multiply by -1 to get positive values
spendings$total_sum <- spendings$total_sum * -1
spendings$Entertainment_sum <- spendings$Entertainment_sum * -1
spendings$Eating_out_sum <- spendings$Eating_out_sum * -1

head(spendings)
## # A tibble: 6 × 5
## # Groups:   Year [2]
##   Year  Month   total_sum Entertainment_sum Eating_out_sum
##   <chr> <chr>       <dbl>             <dbl>          <dbl>
## 1 2022  2022-08      377.             113             67.1
## 2 2022  2022-09      488.             385             35.6
## 3 2022  2022-10     1059.             154.           101. 
## 4 2022  2022-11      494.             114.           130. 
## 5 2022  2022-12     1498.             946            215. 
## 6 2023  2023-01      253.              10.5          174.
suppressPackageStartupMessages(library(zoo))
library(ggplot2)

spendings$Month <- factor(spendings$Month, levels = unique(spendings$Month))

# Create the plot
ggplot(spendings, aes(x = Month)) +
  geom_line(aes(y = total_sum, color = "Total monthly expenditures", group = 1)) +
  geom_line(aes(y = Entertainment_sum, color = "Entertainment expenditures", group = 1)) +
  geom_line(aes(y = Eating_out_sum, color = "Eating Out expenditures", group = 1)) +
  labs(title = "Spending Over Time", x = "Month", y = "EUR") +
  scale_color_manual(name = "Category", 
                     values = c("Total monthly expenditures" = "blue", 
                                "Entertainment expenditures" = "green", 
                                "Eating Out expenditures" = "red")) +
  scale_x_discrete(breaks = unique(spendings$Month)[c(1, 3, 5, 7, 9 ,11)]) +
  theme_minimal()

The higher expenditure can be seen in the months (October, December and April) when I was travelling
around the world and I treated the whole trip, including food, as an entertainment.

Then I was interested in how money is spent when buying clothes. I showed this with a boxplot.

clothes <- subset(filtered_data, Category == "Clothes")$Amount
clothes <- clothes * -1

boxplot(clothes, main = "Boxplot of clothes purschases", xlab = "Clothes", ylab = "EUR")

From the boxplot, we can see that in median I spent a little more than €60 on a single purchase of
clothes in the last year. The maximum I spent was €160 and the minimum was around €25.
Since the boxplot has not detected any outlier, I can assume that I didn’t make any mistake
at entering the details of the purchase of clothes.

Task 2

body_mass <- read.table("./Body mass.csv", header=TRUE, sep=";", dec=",")
head(body_mass) 
##   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

Descriptions:
- ID: identification number of student
- Mass: weight of student in kilograms

2.1 Show the descriptive statistics of body mass and its distribution with the histogram.

summary(body_mass[2])
##       Mass      
##  Min.   :49.70  
##  1st Qu.:60.23  
##  Median :62.80  
##  Mean   :62.88  
##  3rd Qu.:64.50  
##  Max.   :83.20

Median: In the sorted list of students, the middle one weights 62.9 kg.
3rd quartaile: 25% percent of student in school year 2021/2022 is heavier than 64.5 kg.
Max: The heaviest student weights 83.2 kg.

hist(body_mass$Mass,
    xlab = "Mass", 
     ylab = "Frequency", 
     main = "Histogram of body mass")

2.2 Test the following hypothesis H0: mi = 59.5

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

Estimate of arithmetic mean: 62.875
We compare the p-value to alpha(0.05)

H0: mean = 59.5
H1: mean != 59.5
p-value: 0.000234

We reject H0 at p<0.001 and accept H1. Average weight in the 2021/2022 school year is different then
it was in 2018/2019 school year. The average weight increased.
95% confidence interval for arithmetic mean: 61.17 < Mu < 64.58. We can also reject Null hypothesis
at 5% significance, based on this interval, because 59.5 is not included in this interval.

2.3 Explain the results and interpret the effect size.

library(effectsize)
cohens_d(body_mass$Mass,
         mu = 59.5)
## Cohen's d |       95% CI
## ------------------------
## 0.56      | [0.26, 0.86]
## 
## - Deviation from a difference of 59.5.

We reject the null hypothesis so, the average price changed. To find out whether this difference is
big or small we use effect size.
We get standardized measure of effect size. To get interpreter it we use interpret_cohens_d. 

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

We can use different interpretations of effect size, I used “sawilowsky2009” and it tell us
that increase in weight from 2018/2019 to 2021/2022 was medium.

Task 3

3.1 Import the dataset Apartments.xlsx

library(readxl)
apartments_data <- read_xlsx("./Apartments.xlsx")

apartments_data <- as.data.frame(apartments_data) # change it to data frame

head(apartments_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:

  • 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

3.2 Change categorical variables into factors.

apartments_data$ParkingF <- factor(apartments_data$Parking,
                        levels = c (0, 1),
                        labels = c ("No", "Yes")) 

apartments_data$BalconyF <- factor(apartments_data$Balcony,
                        levels = c (0, 1),
                        labels = c ("No", "Yes")) 
head(apartments_data)
##   Age Distance Price Parking Balcony ParkingF BalconyF
## 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
## 6  28       12  1770       0       1       No      Yes

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

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

H0: Mu_price = 1900
H1: Mu_price != 1900

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

We reject H0 at p<0.005 and accept H1. We conclude that true mean price is not equal to 1900 and
it increased.
95% confidence interval for arithmetic mean: 1937.4 < Mu < 2100.4 We can also reject Null hypothesis at
5% significance, based on this interval, because 1900 is not included in this interval.

3.4 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, #Dependent and explanatory variables
           data = apartments_data) #Name of the data frame
summary(fit1)
## 
## Call:
## lm(formula = Price ~ Age, data = apartments_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

Regression coefficient:
H0: Beta1 = 0
H1: Beta1 != 0
P = 0.034 (alpha = 0.05)
Based on p value(p=0.034), we can say that Age has significant effect on price of apartment.
If age of an apartment in years increase by one year, the price of apartment is decreased on average
by 8.98 EUR per square meter, assuming all other explanatory variables, included in the model,
are constant.

Coefficient of correlation:
H0: Ro2 = 0
H1: Ro2 > 0
F=4.647, p = 0.034
We reject null hypothesis at p = 0.034. We can say that population of coefficient of determination is
more than 0, meaning that we found linear relation between price and age of apartment.

Coefficient of determination:
Multiple R2 - 5.3% of variability of apartment price per m2 is explained by linear effect of age.

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

library(car)
## Loading required package: carData
## 
## Attaching package: 'car'
## The following object is masked from 'package:dplyr':
## 
##     recode
scatterplotMatrix(apartments_data[ , c(1, 2, 3)], 
                  smooth = FALSE) 

From this scatter plot matrix I can see that there is no perfect multicolinearity between any of
explanatory variables. The strongest correlation is between age and price, but in our model price is
dependent variable and age is explanatory one, so I do not see any possible problems
with multicolinearity here.

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

fit2 <- lm(Price ~ Age + Distance, #Dependent and explanatory variables
           data = apartments_data) #Name of the data frame

3.7 Chech the multicolinearity with VIF statistics. Explain the findings.

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

If we are not sure what we see on correlation matrix or scatter plot determine whether is here strong
relationship(to strong multicolinearity) between two explanatory variables, then we use
VIF(Variance Inflation Factor).

Theory says that VIF < 5 is okey, so we don’t need to remove any variable, because of big correlation.
I also calculated the mean of the VIF and got 1.002(the closer to 1 the better).

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

apartments_data$StdResid <- round(rstandard(fit2), 3) #outliers
apartments_data$CooksD <- round(cooks.distance(fit2), 3) #influential cases
head(apartments_data)
##   Age Distance Price Parking Balcony ParkingF BalconyF StdResid CooksD
## 1   7       28  1640       0       1       No      Yes   -0.665  0.007
## 2  18        1  2800       1       0      Yes       No    1.783  0.030
## 3   7       28  1660       0       0       No       No   -0.594  0.006
## 4  28       29  1850       0       1       No      Yes    0.754  0.008
## 5  18       18  1640       1       1      Yes      Yes   -1.073  0.005
## 6  28       12  1770       0       1       No      Yes   -0.778  0.005

I calculated standard residuals and cooks distances and append it to the apartments_data.
Then we draw a histogram for both and visually check if some values indicate as outliers or
very influential.

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

Overall we can say it is okey. because all the values are between -3 and 3, but distribution is
not ideal. We have sample bigger than 30 units, so we do Shapfiro-Wilk normality test.

shapiro.test(apartments_data$StdResid)
## 
##  Shapiro-Wilk normality test
## 
## data:  apartments_data$StdResid
## W = 0.95303, p-value = 0.003645

H0: Values is normally distributed.
H1: Variable is not normally distributed.
We reject H0 at p=0.0036. So we do not have normal distributed normal residuals.

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

Logically, we can see that most values have a small cooks distance. However, one value has a gap, and
this would very likely be suitable for removal from the dataset. For the final decision, the table
is sorted to get the largest absolute values for the Standard residuals and Cooks distance.

head(apartments_data[order(apartments_data$StdResid),], 3) #Three units with lowest value of stand. residuals
##    Age Distance Price Parking Balcony ParkingF BalconyF StdResid CooksD
## 53   7        2  1760       0       1       No      Yes   -2.152  0.066
## 13  12       14  1650       0       1       No      Yes   -1.499  0.013
## 72  12       14  1650       0       0       No       No   -1.499  0.013
head(apartments_data[order(-apartments_data$StdResid),], 3) #Three units with highest value of stand. residuals
##    Age Distance Price Parking Balcony ParkingF BalconyF StdResid CooksD
## 38   5       45  2180       1       1      Yes      Yes    2.577  0.320
## 33   2       11  2790       1       0      Yes       No    2.051  0.069
## 2   18        1  2800       1       0      Yes       No    1.783  0.030
head(apartments_data[order(-apartments_data$CooksD),], 3) #Three units with highest value of stand. residuals
##    Age Distance Price Parking Balcony ParkingF BalconyF StdResid CooksD
## 38   5       45  2180       1       1      Yes      Yes    2.577  0.320
## 55  43       37  1740       0       0       No       No    1.445  0.104
## 33   2       11  2790       1       0      Yes       No    2.051  0.069

As we can see from the tables, the same apartment has the highest StaResid and CooksD. I will remove
this apartment because it is the biggest outlier and also has the biggest influence.
I decided to remove only this one because removing more data always creates new outliers.
I know that with the Shapiro_wilk normality test, even though I deleted some data,
I was not able to confirm that the errors are normally distributed, but I will continue as I have
a large enough data set and all the values of the standard residuals are between -3 and 3.

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

I checked the heteroskedacticity first visually and then with a test.

apartments_data$StdFitted <- scale(fit2$fitted.values)  # function scale standardizes values
library(car)
scatterplot(y = apartments_data$StdResid, x = apartments_data$StdFitted,
            ylab = "Standardized residuals",
            xlab = "Standardized fitted values",
            boxplots = FALSE,
            regLine = FALSE,
            smooth = FALSE)

Visually, it looks fine, but to be on the safe side, I also ran a test.

suppressPackageStartupMessages(library(olsrr)) # to exclude package attachment messages in knit
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          =    0.968106 
##  Prob > Chi2   =    0.325153

H0: Variance is constant.
H1: variance is not constant.
We do not reject the H0 hypothesis. So we’ve confirmed that we don’t have heteroskedasticity both
visually and by test.

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

I’ve already done it in 3.8

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

apartments_data <- apartments_data[-38, ] #Removing unit from row 38
fit2 <- lm(Price ~ Age + Distance, 
           data = apartments_data) 
summary(fit2)
## 
## Call:
## lm(formula = Price ~ Age + Distance, data = apartments_data)
## 
## 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

Based on p values, both age and distance have significant effect on price of apartment.

Age
H0: Beta1 = 0
H1: Beta1 != 0
p = 0.044
We reject H0 at p = 0.044.
Explanation of b1 = -6.464
If age of an apartment in years increase by 1 year, the price of apartment per square meter will
decrease in average by 6.46 EUR, assuming all other explanatory variables included in the model,
are constant.

Distance
H0: Beta2 = 0
H1: Beta2 != 0
p < 0.001
We reject H0 at p < 0.001.
If the distance from city center in km increase by 1 km, the price of apartment per square meter
will decrease in average by 22.96 EUR, assuming all other explanatory variables included in
the model, are constant.

3.12 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 + ParkingF + BalconyF, 
           data = apartments_data) 

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

anova(fit2, fit3) #Comparison of two regression models that differ in the number of expl. variables
## Analysis of Variance Table
## 
## Model 1: Price ~ Age + Distance
## Model 2: Price ~ Age + Distance + ParkingF + BalconyF
##   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 2(fit2) is better
H1: Model 3(fit3) is better
p = 0.031
We rejected Null Hypothesis at p = 0.031 Model 3 is better than Model 2, so it explains more
variability in price of apartments. We can say that ParkinF and BalconyF improves the model fit,
because RSS(Residual sum of square) is lower at Fit3.

3.14 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 + ParkingF + BalconyF, data = apartments_data)
## 
## 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 ***
## ParkingFYes  167.531     62.864   2.665  0.00933 ** 
## BalconyFYes  -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

We usually take 5% for alpha, in the extreme cases 10%. If we assume alpha = 0.01, then the variables
age, distance and parking have a significant impact on the price. We cannot explain BalconyF,
because it is a statistically insignificant variable (p = 0.80).

ParkingFYes
H0: beta3 = 0
H1: beta 3 != 0
p = 0.01
Assuming the all others variables are the same, the apartments with parkings have on average
by 167.53 higher price of square meter in EUR compared to apartments without parking(p = 0.01).

t-test hypothesis
H0: all the beta coefficients = 0
H1: not all the beta coefficients = 0 (at least one is not 0)
p < 0.001
We can reject H0 at p < 0.001, that means we found linear relationship between price of apartment and
explanatory variables, included in the model.

3.15 Save fitted values and claculate the residual for apartment ID2.

#save fitted values
apartments_data$fit3_values <- fitted.values(fit3)

#residual
residual = apartments_data[2, 'Price'] - apartments_data[2, 'fit3_values']
print(residual)
## [1] 427.8029

e = y - y_fit
Residual for apartment(ID=2) is 427.8