# [R] Matrix/Vector manipulation

fernando.cabrera at nordea.com fernando.cabrera at nordea.com
Tue Oct 4 08:36:59 CEST 2011

```Stylish, but ifelse only includes a cumsum less or equal than v and ignores the remainder, if v does not fit equally in say the first two weight buckets.

> R  <- c(1.2, 1.3, 1.5)
> W <- c(3,2,5)
> my_cumsum(4, R, W) # should take 3*1.2 + 1*1.3
[1] 4.0
> sum(ifelse(cumsum(W) <= 4, W, 0) * R) # ignores the 1*1.3 part because 3+2 > 4
[1] 3.6

Cheers,
Fer

-----Original Message-----
From: David Reiner [mailto:David.Reiner at xrtrading.com]
Sent: 3. oktober 2011 17:57
To: Cabrera, Fernando Álvarez; r-help at r-project.org
Subject: RE: [R] Matrix/Vector manipulation

sum(ifelse(cumsum(W)<=v, W, 0) * R)

HTH,
David L. Reiner

-----Original Message-----
From: r-help-bounces at r-project.org [mailto:r-help-bounces at r-project.org] On Behalf Of fernando.cabrera at nordea.com
Sent: Monday, October 03, 2011 9:50 AM
To: r-help at r-project.org
Subject: [SPAM] - [R] Matrix/Vector manipulation - Bayesian Filter detected spam

Hi guys,

Have the following problem computing vectors with pure vector algebra and end up reverting to recursion or for-looping.

Function my_cumsum calculates a weighted average (W) of ratios (R), but only up to the given size/volume (v). Now I recurse into the vector (from left to right) with what you have left from the difference of volume minus current weight, and stop when the difference is less than or equal to the current weight.

Vectors W and R have the same length, and v is always a positive integer.

W: {w_1 w_2 .. w_m}
R: {r_1 r_2 .. r_m}

my_cumsum <- function(v, R, W) {
if (v <= W[1]) # check the head
v*R[1]
else
W[1]*R[1] + my_cumsum(v - W[1], R[2:length(R)], W[2:length(W)]) # recurse the tail }

Any help is greatly appreciated!

Fernando Alvarez

"Great ideas originate in the muscles." ~ Thomas A. Edison

______________________________________________
R-help at r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-help