YouTip LogoYouTip

R Func Cumsum

# R cumsum() Function - Calculate Cumulative Sum [![Image 3: R Language Examples](#) R Language Examples](#) The R cumsum() function is used to calculate the cumulative sum of a vector. Cumulative sum (running total) refers to a sequence obtained by adding the current element to all previous elements in order, and is widely used in fields such as financial analysis and inventory statistics. The syntax of the cumsum() function is as follows: cumsum(x) **Parameter Description:** * **x** Input numeric vector. ## Example # Create vector x <-c(1, 2, 3, 4, 5, 6) # Calculate cumulative sum result.cumsum<-cumsum(x) print(result.cumsum) # Calculate cumulative product result.cumprod<-cumprod(x) print(result.cumprod) Execute the above code, the output is: 1 3 6 10 15 21 1 2 6 24 120 720 cumsum() is very practical when simulating cumulative returns: ## Example # Simulate daily returns returns <-c(0.02, -0.01, 0.03, 0.015, -0.005, 0.02, -0.01) # Calculate cumulative returns cumulative <-cumsum(returns) print(paste("Cumulative return:", cumulative)) # Calculate cumulative maximum print(paste("Cumulative max:", cummax(cumulative))) # Calculate cumulative minimum print(paste("Cumulative min:", cummin(cumulative))) Execute the above code, the output is: "Cumulative Return: 0.02" "Cumulative Return: 0.01" "Cumulative Return: 0.04" "Cumulative Return: 0.055" "Cumulative Return: 0.05" "Cumulative Return: 0.07" "Cumulative Return: 0.06" "Cumulative Maximum: 0.02" "Cumulative Maximum: 0.02" "Cumulative Maximum: 0.04" "Cumulative Maximum: 0.055" "Cumulative Maximum: 0.055" "Cumulative Maximum: 0.07" "Cumulative Maximum: 0.07" "Cumulative Minimum: 0.02" "Cumulative Minimum: 0.01" "Cumulative Minimum: 0.01" "Cumulative Minimum: 0.01" "Cumulative Minimum: 0.01" "Cumulative Minimum: 0.01" "Cumulative Minimum: 0.01" [![Image 4: R Language Examples](#) R Language Examples](#)
← R Func DataframeR Func Cor β†’