-
Notifications
You must be signed in to change notification settings - Fork 31
/
Copy pathdiscrete.R
executable file
·90 lines (63 loc) · 2.06 KB
/
discrete.R
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
rdiscrete <- function (n, probs, values = 1:length(probs), ...)
{
sample(values, size=n, replace=TRUE, prob=probs)
}
ddiscrete <- function (x, probs, values = 1:length(probs))
{
if (length(probs) != length(values))
stop("ddiscrete: probs and values must have the same length.")
if (sum(probs < 0) > 0)
stop("ddiscrete: probs must not contain negative values.")
if (!is.array(x) && !is.vector(x) && !is.factor(x))
stop("ddiscrete: x must be an array or a vector or a factor.")
p <- probs/sum(probs)
y <- as.vector(x)
l <- length(y)
z <- rep(0,l)
for (i in 1:l)
if (any(values == y[i]))
z[i] <- p[values == y[i]]
z <- as.numeric(z)
if (is.array(x))
dim(z) <- dim(x)
return(z)
}
pdiscrete <- function (q, probs, values = 1:length(probs))
{
if (length(probs) != length(values))
stop("pdiscrete: probs and values must have the same length.")
if (sum(probs < 0) > 0)
stop("pdiscrete: probs must not contain negative values.")
if (!is.array(q) & !is.vector(q))
stop("pdiscrete: q must be an array or a vector")
p <- probs/sum(probs)
y <- as.vector(q)
l <- length(y)
z <- rep(0,l)
for (i in 1:l)
z[i] <- sum(p[values <= y[i]])
z <- as.numeric(z)
if (is.array(q))
dim(z) <- dim(q)
return(z)
}
qdiscrete <- function (p, probs, values = 1:length(probs))
{
if (length(probs) != length(values))
stop("qdiscrete: probs and values must have the same length.")
if (sum(probs < 0) > 0)
stop("qdiscrete: probs must not contain negative values.")
if (!is.array(p) & !is.vector(p))
stop("qdiscrete: p must be an array or a vector")
probs <- cumsum(probs)/sum(probs)
y <- as.vector(p)
l <- length(y)
z <- rep(0,l)
for (i in 1:l)
z[i] <- length(values) - sum(y[i] <= probs) + 1
z <- as.numeric(z)
z <- values[z]
if (is.array(p))
dim(z) <- dim(p)
return(z)
}