sooki-sooki
sooki-sooki

Reputation: 69

Create a vector with the sum of the positive elements of each column of a m*n numeric matrix in R

I need to create an R function which takes a numeric matrix A of arbitrary format n*m as input and returns a vector that is as long as A's number of columns that contains the sum of the positive elements of each column.

I must do this in 2 ways - the first in a nested loop and the second as a one liner using vector/matrix operations.

So far I have come up with the following code which creates the vector the size of the amounts of columns of matrix A but I can only seem to get it to give me the sum of all positive elements of the matrix instead of each column:

colSumPos(A){

columns <- ncol(A)

v1 <- vector("numeric", columns)

    for(i in 1:columns)
    {
        v1[i] <- sum(A[which(A>0)])
    }
}

Could someone please explain how I get the sum of each column separately and then how I can simplify the code to dispose of the nested loop?

Thanks in advance for the help!

Upvotes: 0

Views: 1233

Answers (2)

GoHan
GoHan

Reputation: 31

You try code folow if you using for loop

sumColum <- function(A){
for(i in 1:nrow(A)){
    for(j in 1:ncol(A)){
        colSums(replace(A, A<=0, NA), na.rm = TRUE)
    }
}
colSums(A)

}

Upvotes: 1

akrun
akrun

Reputation: 887223

We can use apply with MARGIN=2 to loop through the columns and get the sum of elements that are greater than 0

apply(A, 2, function(x) sum(x[x >0], na.rm = TRUE))
#[1] 1.8036685 0.7129192 0.9305136 2.6625824 0.0000000

Or another option is colSums after replacing the values less than or equal to 0 with NA

colSums(A*NA^(A<=0), na.rm = TRUE)
#[1] 1.8036685 0.7129192 0.9305136 2.6625824 0.0000000

Or by more direct approach

colSums(replace(A, A<=0, NA), na.rm = TRUE)
#[1] 1.8036685 0.7129192 0.9305136 2.6625824 0.0000000

Or if there are no NA elements (no need for na.rm=TRUE), we can replace the values that are less than or equal to 0 with 0 and make it compact (as @ikop commented)

colSums(A*(A>0))
#[1] 1.8036685 0.7129192 0.9305136 2.6625824 0.0000000

data

set.seed(24)
A <- matrix(rnorm(25), 5, 5)

Upvotes: 1

Related Questions