List of datasets in R datasets package:
help(package="datasets")
Prewiew of selected dataset:
head(state.x77, 6)
## Population Income Illiteracy Life Exp Murder HS Grad Frost
## Alabama 3615 3624 2.1 69.05 15.1 41.3 20
## Alaska 365 6315 1.5 69.31 11.3 66.7 152
## Arizona 2212 4530 1.8 70.55 7.8 58.1 15
## Arkansas 2110 3378 1.9 70.66 10.1 39.9 65
## California 21198 5114 1.1 71.71 10.3 62.6 20
## Colorado 2541 4884 0.7 72.06 6.8 63.9 166
## Area
## Alabama 50708
## Alaska 566432
## Arizona 113417
## Arkansas 51945
## California 156361
## Colorado 103766
Dataset is representing US state facts and figures. For better understanding of data, we can read description of columns:
-Population: population estimate as of July 1, 1975.
-Income: per capita income (1974).
-Illiteracy: illiteracy (1970, percent of population).
-Life Exp: life expectancy in years (1969–71).
-Murder: murder and non-negligent manslaughter rate per 100,000
population (1976).
-HS Grad: percent high-school graduates (1970).
-Frost: mean number of days with minimum temperature below freezing
(1931–1960) in capital or large city.
-Area: land area in square miles.
This data is appropriate for us because it uses numeric variables, has 50 rows and 8 collumns.
nrow(state.x77)
## [1] 50
ncol(state.x77)
## [1] 8
Now we want to load dataset state.x77 in our work environment.
data(state)
With loading state dataset we get a lot of objects in our work environment that we don’t need. That is why we delete not needed data.
rm("state.center", "state.abb", "state.area", "state.division", "state.name", "state.region")
Now we can assign our dataset in mydata array, which we will use to manipulate with variables. This way we will know which dataset is modified and original will stay unchanged. We could operate on original data, but because of learning purposes, we want to be able to see original data, so that we know if our manipulation with data is correct.
mydata <- state.x77
In the next step we add consecutive numbers as additional column.
mydata <- cbind(mydata, "num"=1:nrow(mydata))
Because we are not interested in mean number of days with minimum temperature below freezing (1931–1960) in capital or large city, we will delete column Frost.
mydata <- mydata[ , -7]
We also want to rename column HS Grad to Highschool grade.
colnames(mydata)[6] ="Highschool_grade"
We can do some descriptive statistics very easily with function describe. To use mentioned function, we need to include psych library.
library(psych)
describe(mydata)
## vars n mean sd median trimmed mad
## Population 1 50 4246.42 4464.49 2838.50 3384.28 2890.33
## Income 2 50 4435.80 614.47 4519.00 4430.08 581.18
## Illiteracy 3 50 1.17 0.61 0.95 1.10 0.52
## Life Exp 4 50 70.88 1.34 70.67 70.92 1.54
## Murder 5 50 7.38 3.69 6.85 7.30 5.19
## Highschool_grade 6 50 53.11 8.08 53.25 53.34 8.60
## Area 7 50 70735.88 85327.30 54277.00 56575.72 35144.29
## num 8 50 25.50 14.58 25.50 25.50 18.53
## min max range skew kurtosis se
## Population 365.00 21198.0 20833.00 1.92 3.75 631.37
## Income 3098.00 6315.0 3217.00 0.20 0.24 86.90
## Illiteracy 0.50 2.8 2.30 0.82 -0.47 0.09
## Life Exp 67.96 73.6 5.64 -0.15 -0.67 0.19
## Murder 1.40 15.1 13.70 0.13 -1.21 0.52
## Highschool_grade 37.80 67.3 29.50 -0.32 -0.88 1.14
## Area 1049.00 566432.0 565383.00 4.10 20.39 12067.10
## num 1.00 50.0 49.00 0.00 -1.27 2.06
With next function we can do some more descriptive statistic. We chose to check quantiles for murder and non-negligent manslaughter rate per 100,000 population (1976).
summary(mydata[ , 5])
## Min. 1st Qu. Median Mean 3rd Qu. Max.
## 1.400 4.350 6.850 7.378 10.675 15.100
Based on the data provided we can form next statements:
25 % of states had murder and non-negligent manslaughter rate in year 1976 smaller than 4.35 people per 100,000 residents.
Median rate of murder and non-negligent manslaughter is 6.85 people per 100,000 residents.
25 % of states had murder and non-negligent manslaughter rate in year 1976 bigger than 10.68 people per 100,000 residents.
We can use function hist, to easily show histogram of life expectancy. There are also other options to do that, but this is the easiest for us.
hist(mydata[, 4],
main = "Life expectancy",
xlab = "Years",
ylab = "Number of states", )
Graph represents how many states has life expectancy between certain
years of age. We can claim that the most states has life expectancy of
70 years for their population.
As for our case scatterplot is not very useful, we will show a simple boxplot regarding the income per capita in 1974.
boxplot(mydata[ , 2])
summary(mydata[ , 2])
## Min. 1st Qu. Median Mean 3rd Qu. Max.
## 3098 3993 4519 4436 4814 6315
The graph shows us firs and third quartiles. From that we can learn that 75 % of states had income below 4810 dollars per capita in year 1974 and 25 % more than that. We can also see, that 25 % of states had income below 3993 dollars per capita. Median income was 4519 dollars. On the graph we can also see one outlayer which represents state where income per capita was more than 6000 dollars. The exact numbers were got from function summary.
For task 2 we need to read the data from .csv file. In the same step we also show firs six collumns of data.
mydata2 <- read.table("./Body mass.csv", header=TRUE, sep=";", dec=",")
head(mydata2, 6)
## 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
Now we want to see descriptive statistics of body mass. Again we use function describe from library psych.
library(psych)
describe(mydata2)
## vars n mean sd median trimmed mad min max range skew
## ID 1 50 25.50 14.58 25.5 25.50 18.53 1.0 50.0 49.0 0.00
## Mass 2 50 62.88 6.01 62.8 62.56 3.34 49.7 83.2 33.5 0.85
## kurtosis se
## ID -1.27 2.06
## Mass 2.11 0.85
We can see that the average weight of ninth graders in school year 2021/2022 was 62.9 kg. Compared to school year 2018/2019 pupils were 3.4 kg heavier on average.
We are also interested in distribution of weight among students. We can easily show it on histogram.
hist(mydata2[, 2],
main = "Body mass 2021/2022",
xlab = "Weight in kg",
ylab = "Number of students", )
We can see that distribution of weight among students is normal. Very
few students weight less than 50 kg and very few more than 80 kg. Most
students weight between 55 and 70 kg.
Null hypothesis is that average weight of students in school year 2021/2022 is the same as in school year 2018/2019. We can define:
H0: Average weight of students in school year 2021/2022 and 2018/2019
is the same.
H1: Average weight of students in school year 2021/2022 and 2018/2019 is
NOT the same.
H0: Mu = 59.5
H1: Mu != 59.5
We can test hypothesis with function t.test().
t.test(mydata2$Mass,
mu = 59.5,
alternative = "two.sided")
##
## One Sample t-test
##
## data: mydata2$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
To determine correctness of null hypothesis, we must check p-value. In our case it is 0.0002, which is less than 0.001. That means that we reject H0. Average weight of students in school year 2021/2022 is not the same as in school year 2018/2019.
library(readxl)
mydata3 <- read_xlsx("./Apartments.xlsx")
head(mydata3) # To see how data is structured.
## # 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
Description:
mydata3 <- as.data.frame(mydata3)
t.test(mydata3$Price,
mu = 1900,
alternative = "two.sided")
##
## One Sample t-test
##
## data: mydata3$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 check the p-value. It is near value 0.001. Although p-value of 0.0047 is still not high enough to support H0 hypothesis. Our conclusion is that average price of apartments is not equal to 1900 eur.
fit1 <- lm(Price ~ Age,
data = mydata3)
summary(fit1)
##
## Call:
## lm(formula = Price ~ Age, data = mydata3)
##
## 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
cor(mydata3)
## Age Distance Price Parking
## Age 1.00000000 0.042908128 -0.230255018 -0.12399145
## Distance 0.04290813 1.000000000 -0.631027945 -0.30711555
## Price -0.23025502 -0.631027945 1.000000000 0.44952621
## Parking -0.12399145 -0.307115547 0.449526214 1.00000000
## Balcony -0.05530363 0.001530351 0.002474935 -0.03406038
## Balcony
## Age -0.055303626
## Distance 0.001530351
## Price 0.002474935
## Parking -0.034060379
## Balcony 1.000000000
Estimate of regression coefficient is in our case - 8. 98. If the age of an apartment increases by 1 year, than the price decreases for 8.98 eur, assuming that all other explanatory variables, included in the model, are constant.
Coefficient of correlation is in our case -0.23, which means that there is weak negative correlation between price and age of an apartment.
Coefficient of determination is in our case 0.053. This means that 5.3 % of variability of price can be explained by the effect of age of an apartment.
library(car)
## Loading required package: carData
##
## Attaching package: 'car'
## The following object is masked from 'package:psych':
##
## logit
scatterplotMatrix(~ mydata3$Price + mydata3$Age + mydata3$Distance,
smooth = FALSE)
We do not detect multicolinearity.
fit2 <- lm(Price ~ Age + Distance,
data = mydata3)
summary(fit2)
##
## Call:
## lm(formula = Price ~ Age + Distance, data = mydata3)
##
## Residuals:
## Min 1Q Median 3Q Max
## -603.23 -219.94 -85.68 211.31 689.58
##
## Coefficients:
## Estimate Std. Error t value Pr(>|t|)
## (Intercept) 2460.101 76.632 32.10 < 2e-16 ***
## Age -7.934 3.225 -2.46 0.016 *
## Distance -20.667 2.748 -7.52 6.18e-11 ***
## ---
## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
##
## Residual standard error: 286.3 on 82 degrees of freedom
## Multiple R-squared: 0.4396, Adjusted R-squared: 0.4259
## F-statistic: 32.16 on 2 and 82 DF, p-value: 4.896e-11
vif(fit2)
## Age Distance
## 1.001845 1.001845
With VIF statistics we found out that Age and Distance are not to strongly correlated. We can assume that as long as VIF numbers are below 5.
mydata3$StdResid <- round(rstandard(fit2), 3) #Standardized residuals
mydata3$CooksD <- round(cooks.distance(fit2), 3) #Cooks distances
hist(mydata3$StdResid,
xlab = "Standardized residuals",
ylab = "Frequency",
main = "Histogram of standardized residuals")
hist(mydata3$CooksD,
xlab = "Cooks distance",
ylab = "Frequency",
main = "Histogram of Cooks distances")
For better representation of results, we draw Histogram of standardized
residuals and Histogram of cooks distances. In the letter we can see
that one unit is too far away from other units. We will remove this one.
After checking in table we are sure, that we must remove line 38.
mydata3 <- mydata3[-38, ]
fit2$fitted.values <- fit2$fitted.values[-38] # Used for the next step.
mydata3$StdFitted <- scale(fit2$fitted.values)
library(car)
scatterplot(y = mydata3$StdResid, x = mydata3$StdFitted,
ylab = "Standardized residuals",
xlab = "Standardized fitted values",
boxplots = FALSE,
regLine = FALSE,
smooth = FALSE)
Scatterplot represents that residuals are randomly distributed around
value 0. This suggests that the assumption that the relationship is
linear is reasonable. We have one residual that stands out and we could
remove it. It is not so critical, but still reasonable to remove.
mydata3 <- mydata3[-54, ]
hist(mydata3$StdResid)
shapiro.test(mydata3$StdResid)
##
## Shapiro-Wilk normality test
##
## data: mydata3$StdResid
## W = 0.94963, p-value = 0.002636
The p-value in our case is 0.0026, which is not less than 0.001. This means that population is normally distributed. We must say also, that the distribution could be better.
fit2 <- lm(Price ~ Age + Distance,
data = mydata3)
summary(fit2)
##
## Call:
## lm(formula = Price ~ Age + Distance, data = mydata3)
##
## Residuals:
## Min 1Q Median 3Q Max
## -627.27 -212.96 -46.23 205.05 578.98
##
## Coefficients:
## Estimate Std. Error t value Pr(>|t|)
## (Intercept) 2490.112 76.189 32.684 < 2e-16 ***
## Age -7.850 3.244 -2.420 0.0178 *
## Distance -23.945 2.826 -8.473 9.53e-13 ***
## ---
## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
##
## Residual standard error: 273.5 on 80 degrees of freedom
## Multiple R-squared: 0.4968, Adjusted R-squared: 0.4842
## F-statistic: 39.49 on 2 and 80 DF, p-value: 1.173e-12
cor(mydata3)
## Age Distance Price Parking
## Age 1.0000000000 0.03071798 -0.21264040 -0.08256350
## Distance 0.0307179840 1.00000000 -0.67822025 -0.34309039
## Price -0.2126404006 -0.67822025 1.00000000 0.44284184
## Parking -0.0825635020 -0.34309039 0.44284184 1.00000000
## Balcony -0.0109811567 -0.01560111 -0.01111362 -0.05917042
## StdResid 0.0006976542 -0.12890023 0.78993995 0.31829428
## CooksD 0.0093568129 -0.23074711 0.41962134 0.07639454
## StdFitted -0.3431057472 -0.94939304 0.70417074 0.34836051
## Balcony StdResid CooksD StdFitted
## Age -0.01098116 0.0006976542 0.009356813 -0.3431057
## Distance -0.01560111 -0.1289002301 -0.230747108 -0.9493930
## Price -0.01111362 0.7899399537 0.419621336 0.7041707
## Parking -0.05917042 0.3182942757 0.076394543 0.3483605
## Balcony 1.00000000 -0.0299015301 0.078933062 0.0181117
## StdResid -0.02990153 1.0000000000 0.403913404 0.1209135
## CooksD 0.07893306 0.4039134039 1.000000000 0.2139021
## StdFitted 0.01811170 0.1209135050 0.213902072 1.0000000
Estimate of regression coefficient for age is - 7.85. If the age of an apartment increases by 1 year, than the price decreases by 7.85 eur, assuming that all other explanatory variables, included in the model, are constant.
If the distance from city center increases for 1 km, than the price for m2 of apartment decreases by 23.95 eur, assuming that all other explanatory variables, included in the model, are constant.
Coefficient of correlation between price and age is in our case -0.21, which means that there is weak negative correlation between price and age of an apartment.
Coefficient of correlation between price and distance is in our case -0.68, which means that there is semi-strong negative correlation between price and distance from city center of an apartment.
Coefficient of determination is in our case 0.4968. This means that 49.68 % of variability of price can be explained by the effect of age of an apartment and distance from city center.
mydata3$BalconyG <- factor(mydata3$Balcony,
levels = c (0, 1),
labels = c ("No", "Yes"))
mydata3$ParkingG <- factor(mydata3$Parking,
levels = c (0, 1),
labels = c ("No", "Yes"))
fit3 <- lm(Price ~ Age + Distance + ParkingG + BalconyG,
data = mydata3)
anova(fit2, fit3)
## Analysis of Variance Table
##
## Model 1: Price ~ Age + Distance
## Model 2: Price ~ Age + Distance + ParkingG + BalconyG
## Res.Df RSS Df Sum of Sq F Pr(>F)
## 1 80 5982100
## 2 78 5458696 2 523404 3.7395 0.02813 *
## ---
## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
We can conclude that model fit3 is better than model fit2.
summary(fit3)
##
## Call:
## lm(formula = Price ~ Age + Distance + ParkingG + BalconyG, data = mydata3)
##
## Residuals:
## Min 1Q Median 3Q Max
## -499.06 -194.33 -32.04 219.03 544.31
##
## Coefficients:
## Estimate Std. Error t value Pr(>|t|)
## (Intercept) 2358.900 93.664 25.185 < 2e-16 ***
## Age -7.197 3.148 -2.286 0.02499 *
## Distance -21.241 2.911 -7.296 2.14e-10 ***
## ParkingGYes 168.921 62.166 2.717 0.00811 **
## BalconyGYes -6.985 58.745 -0.119 0.90566
## ---
## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
##
## Residual standard error: 264.5 on 78 degrees of freedom
## Multiple R-squared: 0.5408, Adjusted R-squared: 0.5173
## F-statistic: 22.97 on 4 and 78 DF, p-value: 1.449e-12
Given the price of apartments, the ones that have parking are 168.9 eur more expensive per m2 on average, compared with the ones that doesn’t have parking, assuming that all other explanatory variables, included in the model, are constant.
Given the price of apartments, the ones that have balcony are 6.99 eur less expensive per m2 on average, compared with the ones that doesn’t have balcony, assuming that all other explanatory variables, included in the model, are constant. This finding is strange, because I would assume that apartment with balcony would be more expensive.
Hypothesis tested with F-statistic:
H0: Model with no independent variables fits the data as well as our
model.
H1: Our model fits the data better than model with no independent
variables.
mydata3$Fitted <- fitted.values(fit3)
print(mydata3$Price[2] - mydata3$Fitted[2])
## [1] 422.9572
Residual for apartment ID2 is 422.96 eur.