-
Notifications
You must be signed in to change notification settings - Fork 52
/
Copy pathmodal.cpp
79 lines (70 loc) · 1.49 KB
/
modal.cpp
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
#include <Rcpp.h>
using namespace Rcpp;
// [[Rcpp::export(name = ".getMode")]]
double getMode(NumericVector values, int ties) {
int n = values.length();
IntegerVector counts(n);
if (ties < 2) {
std::sort(values.begin(), values.end());
}
for (int i = 0; i < n; ++i) {
counts[i] = 0;
int j = 0;
while ((j < i) && (values[i] != values[j])) {
++j;
}
++(counts[j]);
}
int maxCount = 0;
// first (lowest due to sorting)
if (ties == 0) {
for (int i = 1; i < n; ++i) {
if (counts[i] > counts[maxCount]) {
maxCount = i;
}
}
// last
} else if (ties == 1) {
for (int i = 1; i < n; ++i) {
if (counts[i] >= counts[maxCount]) {
maxCount = i;
}
}
// dont care (first, but not sorted)
} else if (ties == 2) {
for (int i = 1; i < n; ++i) {
if (counts[i] > counts[maxCount]) {
maxCount = i;
}
}
// random
} else if (ties == 3) {
int tieCount = 1;
for (int i = 1; i < n; ++i) {
if (counts[i] > counts[maxCount]) {
maxCount = i;
tieCount = 1;
} else if (counts[i] == counts[maxCount]) {
tieCount++;
if (R::runif(0,1) < (1.0 / tieCount)) {
maxCount = i;
}
}
}
// NA
} else {
int tieCount = 1;
for (int i = 1; i < n; ++i) {
if (counts[i] > counts[maxCount]) {
maxCount = i;
tieCount = 1;
} else if (counts[i] == counts[maxCount]) {
tieCount++;
}
}
if (tieCount > 1 ) {
return(NA_REAL);
}
}
return values[maxCount];
}