Skip to content

Instantly share code, notes, and snippets.

@moorepants
Created September 12, 2012 18:56
Show Gist options
  • Save moorepants/3709091 to your computer and use it in GitHub Desktop.
Save moorepants/3709091 to your computer and use it in GitHub Desktop.
Simple example of conditinal sum over columns of R
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