forked from tidyverse/dplyr
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathwindow.cpp
76 lines (68 loc) · 1.75 KB
/
window.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
#include <Rcpp.h>
using namespace Rcpp;
//' Cumulativate versions of any, all, and mean
//'
//' dplyr adds \code{cumall}, \code{cumany}, and \code{cummean} to complete
//' R's set of cumulate functions to match the aggregation functions available
//' in most databases
//'
//' @param x For \code{cumall} & \code{cumany}, a logical vector; for
//' \code{cummean} an integer or numeric vector
//' @export
// [[Rcpp::export]]
LogicalVector cumall(LogicalVector x) {
int n = x.length();
LogicalVector out(n, NA_LOGICAL);
int current = out[0] = x[0];
if( current == NA_LOGICAL) return out ;
if( current == FALSE){
std::fill( out.begin(), out.end(), FALSE ) ;
return out ;
}
for (int i = 1; i < n; i++) {
current = x[i] ;
if( current == NA_LOGICAL ) break ;
if( current == FALSE ){
std::fill( out.begin() + i, out.end(), FALSE ) ;
break ;
}
out[i] = current && out[i - 1];
}
return out;
}
//' @export
//' @rdname cumall
// [[Rcpp::export]]
LogicalVector cumany(LogicalVector x) {
int n = x.length();
LogicalVector out(n, NA_LOGICAL);
int current = out[0] = x[0];
if( current == NA_LOGICAL ) return out ;
if( current == TRUE ){
std::fill( out.begin(), out.end(), TRUE ) ;
return out ;
}
for (int i = 1; i < n; i++) {
current = x[i] ;
if( current == NA_LOGICAL ) break ;
if( current == TRUE ){
std::fill( out.begin() + i, out.end(), TRUE ) ;
break ;
}
out[i] = current || out[i - 1];
}
return out;
}
//' @export
//' @rdname cumall
// [[Rcpp::export]]
NumericVector cummean(NumericVector x) {
int n = x.length();
NumericVector out = no_init(n);
double sum = out[0] = x[0];
for (int i = 1; i < n; i++ ) {
sum += x[i];
out[i] = sum / (i + 1.0);
}
return out;
}