data()
data(package = .packages(all.available = TRUE)) #Code used to find all data sets available in R studio, even the ones not installed. <- This is how i got my data set in package "datasets"
mydata <- force(iris)
head(mydata)
## Sepal.Length Sepal.Width Petal.Length Petal.Width Species
## 1 5.1 3.5 1.4 0.2 setosa
## 2 4.9 3.0 1.4 0.2 setosa
## 3 4.7 3.2 1.3 0.2 setosa
## 4 4.6 3.1 1.5 0.2 setosa
## 5 5.0 3.6 1.4 0.2 setosa
## 6 5.4 3.9 1.7 0.4 setosa
Description of Variables: Sepal Lenght: the length of the sepal of the iris flowers. It is measured in centimeters. Sepal Width: the width of the sepal of the iris flowers. It is also measured in centimeters. Petal Lenght: the length of the petal of the iris flowers. It is measured in centimeters. Petal lenght: the width of the petal of the iris flowers. It is also measured in centimeters. Species: This variable represents the species of the iris flowers. It is a categorical variable with three possible values: Setosa, Versicolor, and Virginica.
library("dplyr")
##
## Attaching package: 'dplyr'
## The following objects are masked from 'package:stats':
##
## filter, lag
## The following objects are masked from 'package:base':
##
## intersect, setdiff, setequal, union
mydata <- dplyr::mutate(mydata, ID = row_number()) #Adding additional variable ID
head((mydata), 5)
## Sepal.Length Sepal.Width Petal.Length Petal.Width Species ID
## 1 5.1 3.5 1.4 0.2 setosa 1
## 2 4.9 3.0 1.4 0.2 setosa 2
## 3 4.7 3.2 1.3 0.2 setosa 3
## 4 4.6 3.1 1.5 0.2 setosa 4
## 5 5.0 3.6 1.4 0.2 setosa 5
mydata <- mydata[c(6, 5, 1, 2, 3, 4)]
colnames(mydata) <- c("ID", "Plants", "Sepal.Length", "Sepal.Width", "Petal.Length", "Petal.Width")
tail(mydata, 8)
## ID Plants Sepal.Length Sepal.Width Petal.Length Petal.Width
## 143 143 virginica 5.8 2.7 5.1 1.9
## 144 144 virginica 6.8 3.2 5.9 2.3
## 145 145 virginica 6.7 3.3 5.7 2.5
## 146 146 virginica 6.7 3.0 5.2 2.3
## 147 147 virginica 6.3 2.5 5.0 1.9
## 148 148 virginica 6.5 3.0 5.2 2.0
## 149 149 virginica 6.2 3.4 5.4 2.3
## 150 150 virginica 5.9 3.0 5.1 1.8
In this step I reorganized the order of column and changed the name of variable species to plants.
summary(mydata[ ,-1]) #Deleting first column
## Plants Sepal.Length Sepal.Width Petal.Length
## setosa :50 Min. :4.300 Min. :2.000 Min. :1.000
## versicolor:50 1st Qu.:5.100 1st Qu.:2.800 1st Qu.:1.600
## virginica :50 Median :5.800 Median :3.000 Median :4.350
## Mean :5.843 Mean :3.057 Mean :3.758
## 3rd Qu.:6.400 3rd Qu.:3.300 3rd Qu.:5.100
## Max. :7.900 Max. :4.400 Max. :6.900
## Petal.Width
## Min. :0.100
## 1st Qu.:0.300
## Median :1.300
## Mean :1.199
## 3rd Qu.:1.800
## Max. :2.500
Explanation of parameters: Q1(Sepal.Lenght):5.1 25% of plants have the lenght of their sepal up to 5.1cm, the rest 75% have longer sepal.
Mean(Sepal.Width): 3.057 Average width of the sepal is 3.057.
Median(Petal.Length): 4.350 This means that 50% of plants had shorter petal than 4.350 and the other 50% had longer petal. 4.350 is the middle number in this dataset.
We can see that in this data set was 150 observations, the minimal width of the petal was 0.1 and the maximum was 2.5. The range is 2.4.
Since plants is categorical variable, the number show us the number of each type of plants.
hist(iris$Sepal.Width, col = "blue",border = "black")
Histogram shows the distribution of sepal width icm for data set. We get
a normally distributed histogram. The size of bins is 0.5cm and most
values fit between value around 2.8cm to 3.0cm.
library(ggplot2)
ggplot(mydata, aes(x = Petal.Length, y = Sepal.Length)) +
geom_point() +
labs(title = "Scatterplot of Sepal Length vs. Petal Length",
x = "Petal Length",
y = "Sepal Length")
When we examine scatter plot, we can see there is a positive linear
correlation between Petal Length and Sepal Length. That means that if
the sepal is longer, also the petal will be longer.
library(ggplot2)
ggplot(mydata, aes(x = Plants, y = Petal.Length))+
theme_bw()+
geom_boxplot()+
ylab("Petal.Length")+
xlab("Plants")
In this boxplot I decided to compare petal lenght by type of plants. We
can indicate that setosa plants have the smallest range for lenght of
petal, meanwhile virginica plants have the biggest range. We can also
indicate that setosa plants have on average the shortest petal and
virginica plants have the longest petal. We can indicate that the
biggest IQR have virginica plants, and smallest setosa plants. With
boxplot we can also indicate outliers, which are present for sentosa and
versicolor plants.
mydata2 <- read.table("~/Desktop/IMB/Bootcamp/R studio/R Take Home Exam/Task 2/Body mass.csv",
header = TRUE,
sep = ";" ,
dec = "," ) #Import data from csv file
head(mydata2)
## 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
#install.packages("pastecs")
library(pastecs)
##
## Attaching package: 'pastecs'
## The following objects are masked from 'package:dplyr':
##
## first, last
round(stat.desc(mydata2[-1]), 2)
## Mass
## nbr.val 50.00
## nbr.null 0.00
## nbr.na 0.00
## min 49.70
## max 83.20
## range 33.50
## sum 3143.80
## median 62.80
## mean 62.88
## SE.mean 0.85
## CI.mean.0.95 1.71
## var 36.14
## std.dev 6.01
## coef.var 0.10
#For descriptive statistics, I decided to use stat. desc. function, but i wrapped it in function round to show 2 decimal places, instead of 7.
library(ggplot2)
ggplot(mydata2, aes(x = Mass)) +
theme_bw()+
geom_histogram(binwidth = 5, colour = "black", fill = "darkseagreen")+
ggtitle("Distribution of body mass among 9th-graders during the year of 2021/22")+
ylab("Frequency")+
xlab("Body mass (kg)")
#####Test the following hypothesis with program R: 𝐻0: 𝜇 = 59.5.
H0: Mu = 59.5 kg. H1: Mu =/ 59.5 kg.
t.test(mydata2$Mass,
mu = 59.5,
alternative = "two.sided") #Testing hypothesis with t-test
##
## 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
With this t-test we researched already before stated H0 and H1. We perform two tailed test, because we are checking only if the average mass in 2021/22 in equal or not to the one in 2018/19. Our p- value is 0.0002 and a=5%.When we compare p-value with significance level a, we can reject H0. Therefore we can say that the mean in 2021/22 is not the same as in 2018/19. The mean of 2021/22 is actually higher. The 95% confidence interval also indicates that we can state with 95% confidence that the population mean for 2021/2022 falls within the range of 61.17 to 64.58. Because the value 59.5 (which is the mean for 2018/19) is not included we can reject H0 at 5%.
#install.packages("effectsize")
library(effectsize)
cohens_d(mydata2$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")
## [1] "medium"
## (Rules: sawilowsky2009)
We can conclude that the effect size is medium.
#install.packages("readxl")
library(readxl)
mydata3 <- read_xlsx("~/Desktop/IMB/Bootcamp/R studio/R Take Home Exam/Task 3/Apartments.xlsx")
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
mydata3$ParkingFactor <- factor(mydata3$Parking,
levels = c(0, 1),
labels = c("No", "Yes"))
mydata3$BalconyFactor <- factor(mydata3$Balcony,
levels = c(0, 1),
labels = c("No", "Yes"))
str(mydata3)
## tibble [85 × 7] (S3: tbl_df/tbl/data.frame)
## $ Age : num [1:85] 7 18 7 28 18 28 14 18 22 25 ...
## $ Distance : num [1:85] 28 1 28 29 18 12 20 6 7 2 ...
## $ Price : num [1:85] 1640 2800 1660 1850 1640 1770 1850 1970 2270 2570 ...
## $ Parking : num [1:85] 0 1 0 0 1 0 0 1 1 1 ...
## $ Balcony : num [1:85] 1 0 0 1 1 1 1 1 0 0 ...
## $ ParkingFactor: Factor w/ 2 levels "No","Yes": 1 2 1 1 2 1 1 2 2 2 ...
## $ BalconyFactor: Factor w/ 2 levels "No","Yes": 2 1 1 2 2 2 2 2 1 1 ...
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
H0: mu = 1900 H1: mu =/ 1900
I can conclude that the mean price of apartments is not equal to 1900 at a 5% significance level. As a result we can reject null hypothesis. The 95% confidence interval also indicates that we can state with 95% confidence that the population mean falls within the range of 1937.443 to 2100.440. Because 1900 doesnt fall in 95% confidence interval, we can also reject null hypothesis at 5% significance level.
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$Price, mydata3$Age) #Coefficient of Correlation
## [1] -0.230255
Price = 2185.455 - 8.975 x Age
H0: B1 = 0 H1: B1 =/ 0
If age increase by 1 year, the price per square meter will on average decrease by 8.975 if all else stays equal. We reject H0 at p-value < 0.05. We found out that age statistically affects price.
r2 is the coefficient of determination, which is in this case 0.05302. It tells us that 5.302% of the variability in the price is explained by the effect of age.
Pearson correlation coefficient of -0.230255 indicates a weak negative linear relationship
library(car)
## Loading required package: carData
##
## Attaching package: 'car'
## The following object is masked from 'package:dplyr':
##
## recode
scatterplotMatrix(mydata3[ , 1:3],
smooth = FALSE) #Scatterplot matrix
When we check the scatter plot, we can see that the slope of the line,
between two explanatory variables which are Age and Distance, is close
to 0. This suggests no significant correlation between the variables and
no multicollinearity issue.
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
mean(vif(fit2)) #Multicolearity
## [1] 1.001845
With VIF function we check for the presence of multicollinearity, which occurs when two or more independent variables in a regression model are highly correlated with each other. Because in this case VIF is around 1 (low) that means there is no issue with multicollinearity.
mydata3$StdResid <- round(rstandard(fit2), 3) #Standardized Residuals
head(mydata3[order(-mydata3$StdResid), ])
## # A tibble: 6 × 8
## Age Distance Price Parking Balcony ParkingFactor BalconyFactor StdResid
## <dbl> <dbl> <dbl> <dbl> <dbl> <fct> <fct> <dbl>
## 1 5 45 2180 1 1 Yes Yes 2.58
## 2 2 11 2790 1 0 Yes No 2.05
## 3 18 1 2800 1 0 Yes No 1.78
## 4 18 1 2800 1 1 Yes Yes 1.78
## 5 8 2 2820 1 0 Yes No 1.66
## 6 10 1 2810 0 0 No No 1.60
tail(mydata3[order(-mydata3$StdResid), ])
## # A tibble: 6 × 8
## Age Distance Price Parking Balcony ParkingFactor BalconyFactor StdResid
## <dbl> <dbl> <dbl> <dbl> <dbl> <fct> <fct> <dbl>
## 1 24 5 1830 1 0 Yes No -1.19
## 2 14 16 1660 0 1 No Yes -1.26
## 3 13 8 1800 0 0 No No -1.38
## 4 12 14 1650 0 1 No Yes -1.50
## 5 12 14 1650 0 0 No No -1.50
## 6 7 2 1760 0 1 No Yes -2.15
hist(mydata3$StdResid,
xlab = "Standardized Residuals",
ylab = "Frequency",
main = "Histogram of Standardized Residuals")
mydata3$CooksD <- round(cooks.distance(fit2), 3)
head(mydata3[order(-mydata3$CooksD), ])
## # A tibble: 6 × 9
## Age Distance Price Parking Balcony ParkingFactor BalconyFactor StdResid
## <dbl> <dbl> <dbl> <dbl> <dbl> <fct> <fct> <dbl>
## 1 5 45 2180 1 1 Yes Yes 2.58
## 2 43 37 1740 0 0 No No 1.44
## 3 2 11 2790 1 0 Yes No 2.05
## 4 7 2 1760 0 1 No Yes -2.15
## 5 37 3 2540 1 1 Yes Yes 1.58
## 6 40 2 2400 0 1 No Yes 1.09
## # ℹ 1 more variable: CooksD <dbl>
hist(mydata3$CooksD,
xlab = "Cooks distance",
ylab = "Frequency",
main = "Histogram of Cooks distances")
When we check standardized Residuals, we find out that none of them fall
above 3 or bellow -3, which would mean we would automatically remove
them as outliers. However, when we check into Cooks distance, we can see
that one observation in particular has a significantly higher cooks
distance than others. A significantly higher Cook’s distance for one
observation means significant impact on the regression model. When we
check back again we see that standardized residual of that same
observation was more close to 3 and had a value of 2.577, I decided to
eliminate it.
This will be done later when estimating fit 2 again in order to avoid problems when completing the next 2 exercises. In the next 2 exercises I will use the regression with the “outlier” included.
mydata3$StdFittedValues <- scale(fit2$fitted.values)
scatterplot(y = mydata3$StdResid, x = mydata3$StdFittedValues,
ylab = "Standardized residuals",
xlab = "Standardized fitted values",
boxplots = FALSE,
regLine = FALSE,
smooth = FALSE)
In this case, we get a scatterplot with constant variance of
standardized residuals, therefore we can conclude there is
homoskedasticity.
hist(mydata3$StdResid,
prob = TRUE,
xlab = "Standardized residuals",
ylab = "Density",
main = "Histogram of standardized residuals")
curve(dnorm(x, mean = mean(mydata3$StdResid), sd = sd(mydata3$StdResid)),
add = TRUE,
lwd = 2,
col = "red")
shapiro.test(mydata3$StdResid)
##
## Shapiro-Wilk normality test
##
## data: mydata3$StdResid
## W = 0.95303, p-value = 0.003645
H0 : variable is normally distributed H1 : variable is not normally distributed
Already from the first histogram, we can see that the standardized residuals are not distributed normally. Furthermore, When we test it with the Shapiro-Wilk normality test, we can see that p-value is 0.003645, therefore we can reject the null hypothesis at a 5% significance level.
mydata3 <- mydata3[!(mydata3$CooksD == 0.320), ]
head(mydata3[order(-mydata3$CooksD), ])
## # A tibble: 6 × 10
## Age Distance Price Parking Balcony ParkingFactor BalconyFactor StdResid
## <dbl> <dbl> <dbl> <dbl> <dbl> <fct> <fct> <dbl>
## 1 43 37 1740 0 0 No No 1.44
## 2 2 11 2790 1 0 Yes No 2.05
## 3 7 2 1760 0 1 No Yes -2.15
## 4 37 3 2540 1 1 Yes Yes 1.58
## 5 40 2 2400 0 1 No Yes 1.09
## 6 8 2 2820 1 0 Yes No 1.66
## # ℹ 2 more variables: CooksD <dbl>, StdFittedValues <dbl[,1]>
fit2 <- lm(Price ~ Age + Distance,
data = mydata3)
summary(fit2) #Results of regression model
##
## Call:
## lm(formula = Price ~ Age + Distance, data = mydata3)
##
## 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
sqrt(summary(fit2)$r.squared) #Cofficient of multiple correlation
## [1] 0.6955609
In this step i first removed the observation that i before with cooks distance, decided it had to be removed. then i estimated fit2, to update the regression model.
Price = 2456.076 - 6.464 x Age - 22.955 x Distance
H0: Beta1 = 0 H1: Beta1 =/ 0 p<0.001
H0: Beta2 = 0 H1: Beta2 =/ 0 p<0.005
H0: Beta3 = 0 H1: Beta3 =/ 0 p<0.001
The intercept coefficient means that on average if Age and Distance are 0 and everything else stays the same the price will be 2456.076. The regression coefficient for Age tells us the if Age increases by 1, the price will on average decrease by 6.464, assuming everything else in the model stays constant. The regression coefficient for Distance tells us the if Distance increases by 1, the price will on average decrease by 22.955, assuming everything else in the model stays constant.
For each of the 3 coefficients, we can reject the null hypothesis at 5% significane level, beacuse p-value is below 0.05
r2 s the coefficient of determination, which is in this case 0.4838. 48.38% of the variability in the price is explained by linear effect of age and distance.
Multiple coefficient of correlation = 0.6955609. There is a moderate linear relationship between Price and the 2 explanatory variables included in the model.
fit3 <- lm(Price ~ Age + Distance + ParkingFactor + BalconyFactor,
data = mydata3)
anova(fit2, fit3) #Comparison of regression models that differ in the number of expl. variables
## 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 is better H1: Model 2 is better
p < 0.05
At a 5% significance level, we can reject the null hypothesis at p<0.05 and say that fit3 (more complex) in a better fit.
summary(fit3)
##
## Call:
## lm(formula = Price ~ Age + Distance + ParkingFactor + BalconyFactor,
## data = mydata3)
##
## 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
The regression coefficient for parking tells us that if the apartment has a parking spot the price will on average be higher by 167.531, if everything else stays constant. It also has a p value< 0.01 so we can say at a 1% level of significance that the coefficient is not equal to 0. The coefficient for balcony has a p-value of 0.79795, therefore we can not say that the coefficient is not equal to 0.
F-statistic H0: the population coefficient of determination equals to 0 a H1: the population coefficient of determination is greater than 0.
mydata3$FittedValues <- fitted.values(fit3)
mydata3$Residuals <- residuals(fit3)
round(mydata3[2, 12], 2)
## # A tibble: 1 × 1
## Residuals
## <dbl>
## 1 428.
The residual for apartment ID indicates that the actual apartment price exceeds the estimated regression value by 427.8 units.