Load data in the workspace by executing:
source("http://www3.nd.edu/~steve/computing_with_data_2014/9_Functions_matrices_lists/work_along_data_S9.R")
We can compute with these sums in one of two ways.
Method 1:
#Create vector for each column
col1 <- c(mat2[,1])
col2 <- c(mat2[,2])
col3 <- c(mat2[,3])
col4 <- c(mat2[,4])
col5 <- c(mat2[,5])
col6 <- c(mat2[,6])
#Find non negative sums
sum(col1[col1 > 0])
## [1] 0.2352207
sum(col2[col2 > 0])
## [1] 0.1402782
sum(col3[col3 > 0])
## [1] 3.037219
sum(col4[col4 > 0])
## [1] 0.3641867
sum(col5[col5 > 0])
## [1] 1.224913
sum(col6[col6 > 0])
## [1] 3.507554
Alternatively, we can use the apply function to compute the sums in a more concise manner.
Method 2:
#Write a function that returns the sum of nonnegative numbers
pos_sum <- function(x){
sum(x[x > 0])
}
#With the defined function, we can drastically simplify nonnegative column sums
col_pos_sums <- apply(mat2, 2, pos_sum)
col_pos_sums
## [1] 0.2352207 0.1402782 3.0372189 0.3641867 1.2249126 3.5075542