forked from tidyverse/dplyr
-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfuns.cpp
95 lines (78 loc) · 1.71 KB
/
funs.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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
#include "dplyr.h"
SEXP dplyr_cumall(SEXP x) {
R_xlen_t n = XLENGTH(x);
SEXP out = PROTECT(Rf_allocVector(LGLSXP, n));
int* p_x = LOGICAL(x);
int* p_out = LOGICAL(out);
// set out[i] to TRUE as long as x[i] is TRUE
R_xlen_t i = 0 ;
for (; i < n; i++, ++p_x, ++p_out) {
if (*p_x == TRUE) {
*p_out = TRUE;
} else {
break;
}
}
if (i != n) {
// set to NA as long as x[i] is NA or TRUE
for (; i < n; i++, ++p_x, ++p_out) {
if (*p_x == FALSE) {
break;
}
*p_out = NA_LOGICAL;
}
// set remaining to FALSE
if (i != n) {
for (; i < n; i++, ++p_x, ++p_out) {
*p_out = FALSE;
}
}
}
UNPROTECT(1);
return out;
}
SEXP dplyr_cumany(SEXP x) {
R_xlen_t n = XLENGTH(x);
SEXP out = PROTECT(Rf_allocVector(LGLSXP, n));
int* p_x = LOGICAL(x);
int* p_out = LOGICAL(out);
// nothing to do as long as x[i] is FALSE
R_xlen_t i = 0 ;
for (; i < n; i++, ++p_x, ++p_out) {
if (*p_x == FALSE) {
*p_out = FALSE;
} else {
break;
}
}
if (i < n) {
// set to NA as long as x[i] is NA or FALSE
for (; i < n; i++, ++p_x, ++p_out) {
if (*p_x == TRUE) {
break;
}
*p_out = NA_LOGICAL;
}
if (i < n) {
// then if we are here, the rest is TRUE
for (; i < n; i++, ++p_out) {
*p_out = TRUE;
}
}
}
UNPROTECT(1);
return out;
}
SEXP dplyr_cummean(SEXP x) {
R_xlen_t n = XLENGTH(x);
SEXP out = PROTECT(Rf_allocVector(REALSXP, n));
double* p_out = REAL(out);
double* p_x = REAL(x);
double sum = 0.0;
for (R_xlen_t i = 0; i < n; i++, ++p_x, ++p_out) {
sum += *p_x;
*p_out = sum / (i + 1.0);
}
UNPROTECT(1);
return out;
}