c("DescTools")
wants <- wants %in% rownames(installed.packages())
has <-if(any(!has)) install.packages(wants[!has])
RunsTest()
from package DescTools
factor(c("f", "m", "m", "f", "m", "f", "f", "f"))
queue <-library(DescTools)
RunsTest(queue, alternative="greater")
Runs Test for Randomness
data: queue
runs = 5, m = 5, n = 3, p-value = 0.5714
alternative hypothesis: true number of runs is greater than expected
table(queue)
Nj <- rle(levels(queue)[as.numeric(queue)])) (runs <-
Run Length Encoding
lengths: int [1:5] 1 2 1 1 3
values : chr [1:5] "f" "m" "f" "m" "f"
length(runs$lengths)) (rr <-
[1] 5
table(runs$values)[1]) (rr1 <-
f
3
table(runs$values)[2]) (rr2 <-
m
2
function(r1, r2, n1, n2) {
getP <-# iterations of a symbol <= total number of this symbol?
stopifnot(r1 <= n1, r2 <= n2)
# probability in case r1+r2 is uneven
(choose(n1-1, r1-1) * choose(n2-1, r2-1)) / choose(n1+n2, n1)
p <-
# probability in case r1+r2 is even: twice the uneven case
ifelse(((r1+r2) %% 2) == 0, 2*p, p)
}
Nj[1]
n1 <- Nj[2]
n2 <- sum(Nj)
N <- 2
rMin <- ifelse(n1 == n2, N, 2*min(n1, n2) + 1)) (rMax <-
f
7
.2 <- getP(3, 2, n1, n2)
p3.3 <- getP(2, 3, n1, n2)
p2.3 <- getP(3, 3, n1, n2)
p3.3 <- getP(4, 3, n1, n2) p4
p3.2 + p2.3 + p3.3 + p4.3) (pGrEq <-
[1] 0.5714286
.2 <- getP(2, 2, n1, n2)
p2.2 <- getP(1, 2, n1, n2)
p1.1 <- getP(2, 1, n1, n2)
p2.1 <- getP(1, 1, n1, n2) p1
p2.2 + p1.2 + p2.1 + p1.1) (pLess <-
[1] 0.4285714
+ pLess pGrEq
[1] 1
1 + ((2*n1*n2) / N)
muR <- (2*n1*n2*(2*n1*n2 - N)) / (N^2 * (N-1))
varR <- (rr-muR) / sqrt(varR)
rZ <- 1-pnorm(rZ)) (pVal <-
f
0.4184066
try(detach(package:DescTools))
R markdown - markdown - R code - all posts