Skip to content

Instantly share code, notes, and snippets.

@arq5x
Created July 13, 2011 02:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save arq5x/1079605 to your computer and use it in GitHub Desktop.
Save arq5x/1079605 to your computer and use it in GitHub Desktop.
R tips and tricks
########################################
# 1. Counting the discrete occurrences
# of a value in each column of a
# matrix. Store the count for each
# column in a new vector whose size
# is the number of columns in the
# matrix.
########################################
# make a 3x3 matrix with columns
# having 0, 1, and 2 zeros
# [,1] [,2] [,3]
# [1,] 1 0 0
# [2,] 2 1 0
# [3,] 3 1 1
m = matrix(c(1,2,3,0,1,1,0,0,1), nrow=3)
# setup a vector whose size is equal to the
# the number of columns in m.
num_zeros = mat.or.vec(ncol(x), 1)
# for each column, count the number
# of zeros and store the result in the
# ith bucket in our num_zeros
# vector.
for (i in seq(1, ncol(m))) {
num_zeros[i] = sum(m[,i]==0)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment