Shuklaswag
Shuklaswag

Reputation: 1023

Creating a cumulative distribution within a column of a matrix in R

I have a situation where there are c probability distributions. Each distribution has r possiblities. So I can model this with a (r x c) matrix where the c'th column represents the c'th probability distribution. The element at [r,c] represents the probability of getting the r'th possibility from the c'th probability distribution. I name this matrix probDist.

I want to generate a cumulative probability distribution matrix, so that each element at [r,c] in the matrix is the sum of the elements from [1,c] to [r-1,c].

I am coding in R. Currently, my code is as follows:

cumProbDist <- probDist
for(c in 1:ncol(probDist))
    cumProbDist[c] <- cumsum(probDist[c])

Which works correctly, but I am aware that the for function is strongly frowned upon in R code due to being inefficient. How may I rewrite this chunk of code to utilize the *apply family of functions (or something similarly efficient) instead?

Upvotes: 0

Views: 300

Answers (1)

Constantine
Constantine

Reputation: 488

cumProbDist = apply(probDist,2,cumsum)

Upvotes: 1

Related Questions