[R] R conditional matrix operations - advanced condition

Berend Hasselman bhh at xs4all.nl
Fri Mar 23 19:50:36 CET 2012

On 23-03-2012, at 17:29, Lukasz Kielpinski wrote:

> Hello List!
> I stumbled across an efficiency problem - calculation that would be
> probably done very fast as a matrix operation I must perform as a
> for-loop.
> My intention was to do a conditional operation in matrix depending on
> the information in first column (summing as many data points from
> vector my_data as the number specified in the first column of the
> matrix) but the result is that the function takes the condition only
> from the first row of column for calculations in every row.
> Is it possible to solve this problem as a matrix calculation or I have
> to iterate over each row? (which I suppose is much slower)
> #problem looks like:
> my_mat <- matrix(1:50,ncol=2)
> my_mat <- cbind(my_mat,0)     #here I have a matrix with empty third
> column where I want to store my results
> my_data <- rnorm(25) #this is a dataset I want to use for filling the
> third column
> #and I did
> my_mat[,3] <- sum(my_data[1:my_mat[,1]]) + my_mat[,2]
> #which didn't work as I expected

If I understand that this correctly I think you should do this

my_data.csum <- cumsum(my_data)
my_mat[,3] <- my_data.csum[my_mat[,1]] + my_mat[,2]


More information about the R-help mailing list