R语言:如何对向量应用自定义累积函数(替代cumsum实现任意逻辑)
cumsum) Great question! You're looking for a way to build a custom cumulative vector—like your cumulative sum of squares example—but with the flexibility to use any arbitrary function. Let's break this down step by step.
1. Quick Fix for Your Cumulative Sum of Squares
For your exact scenario (summing squares cumulatively), the simplest approach is to first square each element of x, then use base R's built-in cumsum:
x <- c(1,2,3,4,5,6,7,8) y <- cumsum(x^2) # Output: 1 5 14 30 55 91 140 204
This gives you exactly the a1=1², a2=1²+2²,... result you need.
2. General Solution: Custom Cumulative Functions
If you want to extend this to any arbitrary function (not just squaring), you have two solid options in R:
Option 1: Base R with Reduce
The Reduce function lets you apply a binary function sequentially over a vector, and setting accumulate=TRUE keeps track of every intermediate result. Here's a reusable function:
# Define a general cumulative function custom_cumulate <- function(input_vec, elem_func) { # elem_func: the function to apply to each element before accumulating Reduce( function(accumulated, current) accumulated + elem_func(current), input_vec, init = 0, accumulate = TRUE )[-1] # Remove the initial 0 to match input length } # Use it for your square sum example y <- custom_cumulate(x, function(val) val^2) # Try another custom operation: cumulative sum of cubes y_cubes <- custom_cumulate(x, function(val) val^3) # Or cumulative sum of (value + 1) y_plus1 <- custom_cumulate(x, function(val) val + 1)
Option 2: Tidyverse with purrr::accumulate
If you use the tidyverse, the purrr package's accumulate function makes this even more readable. It uses formula syntax for the cumulative logic:
library(purrr) # Cumulative sum of squares y <- accumulate(x, ~ .x + .y^2, .init = 0)[-1] # .x = previous accumulated value, .y = current element
Both approaches let you swap out the element-wise function (like squaring, cubing, etc.) to fit any cumulative logic you need.
内容的提问来源于stack exchange,提问作者Ilya Vishnyakov

