Created
September 12, 2012 18:56
-
-
Save moorepants/3709091 to your computer and use it in GitHub Desktop.
Simple example of conditinal sum over columns of R
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
d <- as.data.frame(replicate(10, rnorm(20))) | |
# sum colums method 1 | |
colSums(d) | |
# method 2 | |
apply(d, 2, sum) | |
# now sum the columns only if the first column has values greater than 2 | |
colSums(subset(d, V1 > 2)) | |
# now sum if any column is greater than 0 on a per column basis | |
condSum <- function(x){ | |
sum(x[x > 0]) | |
} | |
apply(d, 2, condSum) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment