# vector of normal deviates
a.norms <- rnorm(100)
# matrix with 20 rows (and 5 columns)
a.mat <- matrix(a.norms, nrow = 20)
# matrix with 5 columns (and 20 rows)
b.mat <- matrix(a.norms, ncol = 5)
# test whether these matrices are exactly the same
identical(a.mat, b.mat)
# first 5 letters of the alphabet
letters[1:5]
# assign as column names
colnames(a.mat) <- letters[1:5]
colnames(a.mat)
# are they still identical?
identical(a.mat, b.mat)
# nope, because colnames are different
# what's different?
all.equal(a.mat, b.mat)
# apply is AWESOME!!!
# for each column (2=column), calculate the sd
a.vec <- apply(a.mat, 2, sd)
a.vec
# use "anonymous" function to calculate sd()
b.vec <- apply(a.mat, 2, function(X) {
sd(X)
}
)
b.vec
# they're the same! Horrah.
all.equal(a.vec, b.vec)
# sd and mean
c.vec <- apply(a.mat, 2, function(X) {
c(sd(X), mean(X))
})
# apply "applies" to columns, so in each column we get the two values
# sd and mean
c.vec
# transpose so rows are groups and columns are sd and mean
c.vec <- t(c.vec)
c.vec
colnames(c.vec) <- c("sd", "mean")
c.vec