Problem 21

# Preparation for further convenience

data1 <- mtcars

mpg <- data1$mpg
cyl <- data1$cyl
wt <- data1$wt

df1 <- cbind(mpg,cyl,wt)


# Estimates for location

means <- colMeans(df1)

medians <- apply(df1,2,median)

print(rbind(means,medians))
##              mpg    cyl      wt
## means   20.09062 6.1875 3.21725
## medians 19.20000 6.0000 3.32500
# Estimates for scale


SD <- apply(df1,2,sd)

MADs <- apply(df1,2, mad)

iqr <- apply(df1,2, IQR)

IQR <- iqr/1.349

print(rbind(SD,MADs,IQR))
##           mpg      cyl        wt
## SD   6.026948 1.785922 0.9784574
## MADs 5.411490 2.965200 0.7672455
## IQR  5.467013 2.965159 0.7626019

Problem 22

setwd("~/Desktop/r.data/data")

cats <- read.csv("cats.csv")


# In the following experiment we want to study if cats prefer to drink under flowing water based on a small sample. H0 which we are testing is the assumption that there is no preference to cats regarding water-flow. (alpha = 5% , two sided)


# From this data we can see that there are seemingly big outliers/volatile in the differences. This may indicate that the t.test might me unsuitable


diff <- cats$flow-cats$still

print(diff)
## [1]   7.0 -33.0 116.0  65.0   5.0  17.0 -10.5 -92.5 -23.5
# From the wilcox test we are far from rejecting H0.

wilcox.test(cats$still,cats$flow, paired = T, conf.int = T)
## 
##  Wilcoxon signed rank exact test
## 
## data:  cats$still and cats$flow
## V = 22, p-value = 1
## alternative hypothesis: true location shift is not equal to 0
## 95 percent confidence interval:
##  -60.50  42.75
## sample estimates:
## (pseudo)median 
##          -3.25

Problem 23

setwd("~/Desktop/r.data/data")



water <-  read.csv("water.csv")





at <- water[1:10,]

nat <- water[11:15,]

boxplot(at$pd,nat$pd)

# Comparing the two seperate data we can observe that these are not ideal to compare , since we are comparing quiet different in scale and scope (size, variance e.t.c).



# H0 : no shift in the two gropus ( alpha = 5% , two sided).

wilcox.test(at$pd,nat$pd)
## 
##  Wilcoxon rank sum exact test
## 
## data:  at$pd and nat$pd
## W = 35, p-value = 0.2544
## alternative hypothesis: true location shift is not equal to 0
# From the P-value (0.2544) we fail to reject H0. --> no shift
library("coin")
## Lade nötiges Paket: survival
# error :/
#  wilcox_test(at$pd~nat$pd)

Problem 23c)

perm_test <- function(x1,x2,n) {
  combi <- c(x1,x2)
  tobs = median(x1)-median(x2)
  tsim <- matrix(ncol = n)
  for (i in 1:n) {
    rng <- sample(1:length(combi), length(x1), replace = FALSE)
    gA <- combi[rng]
    gB <- combi[-rng]
    
    mga <- median(gA)
    mgb <- median(gB)
    
    tsim[i] <-  mga - mgb
    
  }
  
 pV <-  sum(abs(tsim) >= abs(tobs))
  
return((pV)/n)
  
}


perm_test(at$pd,nat$pd, n=1000)
## [1] 0.101