Skip to content

Commit 26e8502

Browse files
committed
also factored out INTSXP case to correctly deal with NA
1 parent e57ab83 commit 26e8502

File tree

1 file changed

+24
-0
lines changed
  • inst/include/Rcpp/sugar/functions

1 file changed

+24
-0
lines changed

inst/include/Rcpp/sugar/functions/mean.h

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -110,6 +110,30 @@ class Mean<LGLSXP,NA,T> : public Lazy<double, Mean<LGLSXP,NA,T> > {
110110
const VEC_TYPE& object ;
111111
};
112112

113+
template <bool NA, typename T>
114+
class Mean<INTSXP,NA,T> : public Lazy<double, Mean<INTSXP,NA,T> > {
115+
public:
116+
typedef typename Rcpp::VectorBase<INTSXP,NA,T> VEC_TYPE;
117+
118+
Mean(const VEC_TYPE& object_) : object(object_) {}
119+
120+
double get() const {
121+
IntegerVector input = object;
122+
int n = input.size(); // double pass (as in summary.c)
123+
long double s = std::accumulate(input.begin(), input.end(), 0.0L);
124+
s /= n;
125+
long double t = 0.0;
126+
for (int i = 0; i < n; i++) {
127+
if (input[i] == NA_INTEGER) return NA_REAL;
128+
t += input[i] - s;
129+
}
130+
s += t/n;
131+
return (double)s ;
132+
}
133+
private:
134+
const VEC_TYPE& object ;
135+
};
136+
113137
} // sugar
114138

115139
template <bool NA, typename T>

0 commit comments

Comments
 (0)