I am so new in R and want to write my own R cumsum() function. How can I create the function which takes in a length N vector of values to compute cumulative sums. Thanks
Asked
Active
Viewed 397 times
-3
-
1Are you asking how to write that specific function, or a function in general? If the former, what is your purpose of doing that instead of just using `cumsum()`? – Phil Jun 13 '21 at 14:47
-
3What have you tried? Where are you getting stuck? Right now this isn't a specific programming question that's appropriate for Stack Overflow. If you are new to R, i'd recommend not trying to re-create optimized built in base functions. It's better to just use the existing function. If this is homework for some class or something, you could contact your instructor for guidance. – MrFlick Jun 13 '21 at 17:17
-
Following @MrFlick: if this is homework and you *don't* want to contact your instructor for whatever reason, you should show us how what you've tried to get started. See e.g. [this question on asking HW questions](https://meta.stackoverflow.com/questions/334822/how-do-i-ask-and-answer-homework-questions) – Ben Bolker Jun 13 '21 at 20:54
1 Answers
0
Here's a cumsum function using accumulate
from the {purrr}
package:
alt_cumsum <- function(x) {
require(purrr)
accumulate(x, `+`)
}
Example usage:
> alt_cumsum(1:5)
[1] 1 3 6 10 15

Rory S
- 1,278
- 5
- 17