R Domaca_naloga

Za obe raziskovalni vprasanji bom uporabljal podatkovno bazo znotraj programa R in sicer baza se imenuje iris. Ta baza vsebuje 4 stevilske spremenljivke ter eno kategorialno, podatki se nanasajo na tri razlicne vrste roz.

Prvo raziskovalno vprašanje

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
library(effectsize)
library(ggplot2)
library(psych)
## 
## Attaching package: 'psych'
## The following objects are masked from 'package:ggplot2':
## 
##     %+%, alpha
## The following object is masked from 'package:effectsize':
## 
##     phi
library(car)
## Loading required package: carData
## 
## Attaching package: 'car'
## The following object is masked from 'package:psych':
## 
##     logit
## The following object is masked from 'package:dplyr':
## 
##     recode
library(rstatix)
## 
## Attaching package: 'rstatix'
## The following objects are masked from 'package:effectsize':
## 
##     cohens_d, eta_squared
## The following object is masked from 'package:stats':
## 
##     filter
library(onewaytests)
## 
## Attaching package: 'onewaytests'
## The following object is masked from 'package:psych':
## 
##     describe
library(ggpubr)
library(olsrr)
## 
## Attaching package: 'olsrr'
## The following object is masked from 'package:datasets':
## 
##     rivers
library(estimatr)
data("iris")

# podatki na katerih bom delal

df = iris 

# shranim si jih v spremenljivko

table(df$Species) 
## 
##     setosa versicolor  virginica 
##         50         50         50
# preverim koliko je katerih za kategorialno spremenljivko, če moram zamenjati vrstni red

df$vrsta = with(df, ifelse(Species == "setosa", 1,
                           ifelse(Species == "versicolor", 2, 3))) 

# vseh je 50, tako da mesto ni pomembno

df$Species = as.factor(df$Species) # spremenimo v factor

# naredim preizkus ali je statistično značilna razlika med vrstami in dolžino cveta

vrsta1 = df %>%
  filter(vrsta == 1)

shapiro.test(vrsta1$Petal.Length) # porazdeljeno normalno
## 
##  Shapiro-Wilk normality test
## 
## data:  vrsta1$Petal.Length
## W = 0.95498, p-value = 0.05481
vrsta2 = df %>%
  filter(vrsta == 2)

shapiro.test(vrsta2$Petal.Length) # porazdeljeno normalno
## 
##  Shapiro-Wilk normality test
## 
## data:  vrsta2$Petal.Length
## W = 0.966, p-value = 0.1585
vrsta3 = df %>%
  filter(vrsta == 3)

shapiro.test(vrsta3$Petal.Length) # porazdeljeno normalno
## 
##  Shapiro-Wilk normality test
## 
## data:  vrsta3$Petal.Length
## W = 0.96219, p-value = 0.1098
shapiro.test(df$Petal.Length) # celoten vzorec pa ni porazdeljen normalno
## 
##  Shapiro-Wilk normality test
## 
## data:  df$Petal.Length
## W = 0.87627, p-value = 7.412e-10
rezultat1 = aov(Petal.Length ~ Species,
                data = df)

summary(rezultat1)
##              Df Sum Sq Mean Sq F value Pr(>F)    
## Species       2  437.1  218.55    1180 <2e-16 ***
## Residuals   147   27.2    0.19                   
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
eta_squared(rezultat1)
##   Species 
## 0.9413717
interpret_eta_squared(0.94, rules = "cohen1992") # velik učinek ima vrsta rože na dolžino cvetnega lista
## [1] "large"
## (Rules: cohen1992)
pari = pairwise.t.test(df$Petal.Length, g = df$Species,
                  paired = FALSE,
                  p.adjust.method = "bonferroni")

anova_rezultat1 = aov(Petal.Length ~ Species,
                            data = df)

ggboxplot(df, x = "Species", y = "Petal.Length", add = "point", ylim=c(0,12)) +
  stat_summary(fun = mean, geom = "point", shape = 16, size = 4,
               aes(group = Species), color = "darkred",
               position = position_dodge(width = 0.8)) +
  stat_summary(fun = mean, colour = "darkred",
               position = position_dodge(width = 0.8),
               geom = "text", vjust = -0.5, hjust = -1,
               aes(label = round(after_stat(y), digits = 2), group = Species))

# preizkus nam pokaže, da so razlike med vrstami statistično značilne glede na vrsto in dolžino cvetnega lista

# naredimo še neparametričen preizkus

kruskal_rezultat = kruskal.test(Petal.Length ~ Species,
             data = df)

kruskal_effsize(Petal.Length ~ Species,
                data = df)
## # A tibble: 1 × 5
##   .y.              n effsize method  magnitude
## * <chr>        <int>   <dbl> <chr>   <ord>    
## 1 Petal.Length   150   0.874 eta2[H] large
neparametricen = wilcox.test(df$Petal.Length, g = df$Species,
                             paired = FALSE,
                             p.adjust.method = "bonferroni")

ggboxplot(df, x = "Species", y = "Petal.Length", add = "point", ylim=c(0,12)) +
  stat_summary(fun = median, geom = "point", shape = 16, size = 4,
               aes(group = Species), color = "darkred",
               position = position_dodge(width = 0.8)) +
  stat_summary(fun = median, colour = "darkred",
               position = position_dodge(width = 0.8),
               geom = "text", vjust = -0.5, hjust = -1,
               aes(label = round(after_stat(y), digits = 2), group = Species))

# oba odkrijeta statistično značilne razlike med skupinami vendar bi zaradi vrste podatkov raje izbral parametričen preizkus

Drugo raziskovalno vprašanje

fit = lm(Sepal.Length ~ Sepal.Width + Petal.Length + Species,
         data = df)

summary(fit)
## 
## Call:
## lm(formula = Sepal.Length ~ Sepal.Width + Petal.Length + Species, 
##     data = df)
## 
## Residuals:
##      Min       1Q   Median       3Q      Max 
## -0.82156 -0.20530  0.00638  0.22645  0.74999 
## 
## Coefficients:
##                   Estimate Std. Error t value Pr(>|t|)    
## (Intercept)        2.39039    0.26227   9.114 5.94e-16 ***
## Sepal.Width        0.43222    0.08139   5.310 4.03e-07 ***
## Petal.Length       0.77563    0.06425  12.073  < 2e-16 ***
## Speciesversicolor -0.95581    0.21520  -4.442 1.76e-05 ***
## Speciesvirginica  -1.39410    0.28566  -4.880 2.76e-06 ***
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## Residual standard error: 0.3103 on 145 degrees of freedom
## Multiple R-squared:  0.8633, Adjusted R-squared:  0.8595 
## F-statistic: 228.9 on 4 and 145 DF,  p-value: < 2.2e-16
# opazimo, da so vse statistično značilne za določitev Sepal.Length

vif(fit)
##                   GVIF Df GVIF^(1/(2*Df))
## Sepal.Width   1.946902  1        1.395314
## Petal.Length 19.898536  1        4.460778
## Species      27.111945  2        2.281866
# opazimo, da ima Petal.Length velik GVIF vendar vseeno manjši od 5

df$StdOstanki = round(rstandard(fit), 3)
df$CooksD = round(cooks.distance(fit), 3)

hist(df$StdOstanki,
     xlab = "Standardizirani ostanki",
     ylab = "Frekvenca",
     main = "Histogram standardiziranih ostankov")

shapiro.test(df$StdOstanki) # standardizirani ostanki so normalno porazdeljeni
## 
##  Shapiro-Wilk normality test
## 
## data:  df$StdOstanki
## W = 0.99515, p-value = 0.903
hist(df$CooksD,
     xlab = "Cookove razdalje",
     ylab = "Frekvenca",
     main = "Histogram Cookovih razdalj")

df$ID = seq(1, nrow(df))

head(df[order(df$StdOstanki), c("ID", "StdOstanki")], 3) 
##      ID StdOstanki
## 85   85     -2.679
## 101 101     -2.540
## 107 107     -2.220
head(df[order(-df$StdOstanki), c("ID", "StdOstanki")], 3) # vsi znotraj [-3,3] tako, da ne odstranim nobenega podatka tu
##      ID StdOstanki
## 15   15      2.481
## 136 136      2.213
## 142 142      1.992
head(df[order(-df$CooksD), c("ID", "CooksD")], 3)
##      ID CooksD
## 15   15  0.067
## 107 107  0.066
## 101 101  0.040
df = df %>% filter(!ID %in% c(15, 107)) # odstranim podatka 15 in 107 ker je velika razlika med njimi in ostalimi podatki v Cookovi razdalji in sta to točki z velikim vplivom, ki lahko pokvarita podatke kot naprimer osamelci

fit = lm(Sepal.Length ~ Sepal.Width + Petal.Length + Species,
         data = df) # ponovno naredim regresijo na novih podatkih

df$StdOcena = scale(fit$fitted.values)
df$StdOstanki = round(rstandard(fit), 3)

scatterplot(y = df$StdOstanki, x = df$StdOcena,
            ylab = "Standardizirani ostanki",
            xlab = "Standardizirane ocenjene vrednosti",
            main = "Test za heteroskedasticnost")

ols_test_breusch_pagan(fit) # preverimo se s testom breusch_pagan in opazimo krsitev homoskedasticnosti
## 
##  Breusch Pagan Test for Heteroskedasticity
##  -----------------------------------------
##  Ho: the variance is constant            
##  Ha: the variance is not constant        
## 
##                   Data                   
##  ----------------------------------------
##  Response : Sepal.Length 
##  Variables: fitted values of Sepal.Length 
## 
##         Test Summary          
##  -----------------------------
##  DF            =    1 
##  Chi2          =    6.138282 
##  Prob > Chi2   =    0.01322858
fit_popravek = lm_robust(Sepal.Length ~ Sepal.Width + Petal.Length + Species,
                         se_type = "HC1",
                         data = df) # uporabimo regresijo z Whitovimi robustnimi standardnimi napakami

summary(fit_popravek) # opazimo, da lahko velik del Sepal.Length pojasnimo z temi tremi spremenljivkami ker je Adjusted R-squared 0.87.
## 
## Call:
## lm_robust(formula = Sepal.Length ~ Sepal.Width + Petal.Length + 
##     Species, data = df, se_type = "HC1")
## 
## Standard error type:  HC1 
## 
## Coefficients:
##                   Estimate Std. Error t value  Pr(>|t|) CI Lower CI Upper  DF
## (Intercept)         2.5325    0.23183  10.924 1.413e-20   2.0742   2.9907 143
## Sepal.Width         0.3891    0.07279   5.346 3.478e-07   0.2453   0.5330 143
## Petal.Length        0.7687    0.06195  12.407 1.883e-24   0.6462   0.8911 143
## Speciesversicolor  -0.9489    0.19509  -4.864 2.999e-06  -1.3345  -0.5633 143
## Speciesvirginica   -1.3552    0.27317  -4.961 1.963e-06  -1.8952  -0.8152 143
## 
## Multiple R-squared:  0.8726 ,    Adjusted R-squared:  0.869 
## F-statistic: 276.1 on 4 and 143 DF,  p-value: < 2.2e-16
# opazimo pozitiven vpliv spremenljivk Sepal.Width in Petal.Length na Sepal.Length ter, da imata v povprečju vrsti tako versicolor in virginica manjši Sepal.Length kot vrsta setosa