# Wilcoxon paired example
# mydataframe <- read.delim("http://www.robin-beaumont.co.uk/virtualclassroom/book2data/wilcoxon_paired_ex1.dat", header=TRUE)
### Local ignore:
# mydataframe <- read.delim("D:\\web_sites_mine\\HIcourseweb new\\book2data\\wilcoxon_paired_ex1.dat", header=TRUE)
###
names(mydataframe)
attach(mydataframe)

mydataframe$difference <- mydataframe$post - mydataframe$pre
names(mydataframe)
boxplot(pre, post, mydataframe$difference, col = "grey", names = c("pre","post","difference"),
main= "Boxplots of pre, post and differences") 
summary(mydataframe)
wilcox.test(mydataframe$post, mydataframe$pre, alternative="two.sided", paired=TRUE)
# add CI
wilcox.test(mydataframe$post, mydataframe$pre, alternative="two.sided", paired=TRUE, conf.int=TRUE)

#######
Wilcoxon signed distribution (paired data) 
n<-6
efsize <- n*(n+1)/2
x <- seq(0,efsize)
plot(x, dsignrank(x,n), type="h", xlab="T (rank sum) value", ylab="p", main=paste("Wilcoxon distribution (n =",n,")"))

############################
post<-c(7, 6,8,7,6,9)
pre<-c(1,4,3,5,4,5) 
difference <- post - pre
table(difference)
hist(difference, breaks=length(difference))
cum_freq <- cumsum(table(difference))

###
# to get percentage of ties
(2/length(difference))*100 

################
pre<-c(1,4,8,5,4,5)
post<-c(1,6,3,7,4,9) 
difference <- post - pre
atable <- table(difference)
atable
# now for % of each:
percent <- (atable/length(difference))*100
percent
hist(difference, breaks=length(difference))

################################
# exact
wilcox.exact(x, y, paired = TRUE, alternative = "greater")
# does not return a ci
qperm(at, 0.95)

#######################
#######################
x1<-  c(1,7,19,15,14,25, 31,34,48, 21)
x2<- c(1,7, 3, 7, 4, 9, 10, 13, 31, 8) 

wilcox.test(x1, x2,alternative="two.sided", paired=TRUE, conf.int=TRUE)

difference2 <- x1 - x2
table(difference2)
hist(difference2, breaks=length(difference2))
####################
# using the coin package for permutation null distribution
install.packages("coin", dependencies=TRUE) 
library(coin)
post<-c(7, 6,8,7,6,9)
pre<-c(1,4,3,5,4,5) 
# note unable to request a CI
rst<- wilcoxsign_test(pre ~ post, distribution="exact")
rst

qperm(rst, 0.95)






