Skip to content

Instantly share code, notes, and snippets.

@mcnemesis
Last active March 27, 2019 18:58
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 mcnemesis/31df1b178cd6dda2292ce5f0d1fffbe4 to your computer and use it in GitHub Desktop.
Save mcnemesis/31df1b178cd6dda2292ce5f0d1fffbe4 to your computer and use it in GitHub Desktop.
Exploring R: apply()
# Construct a 5x6 matrix
X <-matrix(rnorm(30), nrow=5, ncol=6)
# Sum the values of each row with `apply()`
X2 <- apply(X, 1, sum)
NROW(X2)
NCOL(X2)
# So the same for each row
X3 <- apply(X, 2, sum)
NROW(X3)
NCOL(X3)
# Lesson: apply() will always output a column vector whether the margin applied was 1/by-row or 2/by-column
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment