Skip to content

Commit 1f97cac

Browse files
committed
minor edit / simplification
1 parent ffc67bb commit 1f97cac

File tree

2 files changed

+12
-52
lines changed

2 files changed

+12
-52
lines changed

_posts/2012-12-22-vector-cumulative-sum.md

+4-44
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,6 @@ src: 2012-12-22-vector-cumulative-sum.cpp
1010
---
1111

1212

13-
1413
The traditional way to compute the cumulative sum of a vector is with a
1514
for loop. This is demonstrated with the function cumsum1().
1615

@@ -35,7 +34,6 @@ NumericVector cumsum1(NumericVector x){
3534
}
3635
{% endhighlight %}
3736

38-
3937
The C++ standard template library (STL) has the partial_sum() function
4038
that computes the cumulative sum of a vector. This is demonstrated with
4139
the function cumsum2().
@@ -50,7 +48,6 @@ NumericVector cumsum2(NumericVector x){
5048
}
5149
{% endhighlight %}
5250

53-
5451
With Rcpp sugar, there is a cumsum() function which makes writing
5552
this function in C++ very similar to using the cumsum function in R.
5653

@@ -61,52 +58,15 @@ NumericVector cumsum_sug(NumericVector x){
6158
}
6259
{% endhighlight %}
6360

61+
And we can of course compare the versions discussed here with the base R variant.
6462

6563
{% highlight r %}
66-
x <- 1:10
67-
cumsum1(x)
68-
{% endhighlight %}
69-
70-
71-
72-
<pre class="output">
73-
[1] 1 3 6 10 15 21 28 36 45 55
74-
</pre>
75-
76-
77-
78-
{% highlight r %}
79-
cumsum2(x)
80-
{% endhighlight %}
81-
82-
83-
84-
<pre class="output">
85-
[1] 1 3 6 10 15 21 28 36 45 55
86-
</pre>
87-
88-
89-
90-
{% highlight r %}
91-
cumsum_sug(x)
64+
x <- 1:10
65+
all.equal(cumsum1(x), cumsum2(x), cumsum_sug(x), cumsum(x))
9266
{% endhighlight %}
9367

9468

9569

9670
<pre class="output">
97-
[1] 1 3 6 10 15 21 28 36 45 55
71+
[1] TRUE
9872
</pre>
99-
100-
101-
102-
{% highlight r %}
103-
# cumsum function in base R
104-
cumsum(x)
105-
{% endhighlight %}
106-
107-
108-
109-
<pre class="output">
110-
[1] 1 3 6 10 15 21 28 36 45 55
111-
</pre>
112-

src/2012-12-22-vector-cumulative-sum.cpp

+8-8
Original file line numberDiff line numberDiff line change
@@ -55,13 +55,13 @@ NumericVector cumsum2(NumericVector x){
5555
NumericVector cumsum_sug(NumericVector x){
5656
return cumsum(x); // compute the result vector and return it
5757
}
58-
59-
/*** R
60-
x <- 1:10
61-
cumsum1(x)
62-
cumsum2(x)
63-
cumsum_sug(x)
64-
# cumsum function in base R
65-
cumsum(x)
58+
59+
/**
60+
* And we can of course compare the versions discussed here with the base R variant.
6661
*/
62+
63+
/*** R
64+
x <- 1:10
65+
all.equal(cumsum1(x), cumsum2(x), cumsum_sug(x), cumsum(x))
66+
*/
6767

0 commit comments

Comments
 (0)