Skip to content

Instantly share code, notes, and snippets.

@karawoo
Last active August 29, 2015 14:10
Show Gist options
  • Save karawoo/51d23dc7ac604d8ce1ea to your computer and use it in GitHub Desktop.
Save karawoo/51d23dc7ac604d8ce1ea to your computer and use it in GitHub Desktop.
# minimal dataset
dat <- data.frame(a = c(1, 5, 2),
b = c(5, 2, 9),
c = c(4, 3, 1))
rowMeans(dat)
# [1] 3.333333 3.333333 4.000000
do.call(rbind, lapply(seq_len(nrow(dat)), function (k) {mean(as.numeric(dat[k, ]))}))
# [,1]
# [1,] 3.333333
# [2,] 3.333333
# [3,] 4.000000
# to use rowMeans but get an output that looks just like the latter:
matrix(rowMeans(dat))
# [,1]
# [1,] 3.333333
# [2,] 3.333333
# [3,] 4.000000
# still using *apply, but less typing:
matrix(apply(dat, 1, function (k) {mean(k)}))
# [,1]
# [1,] 3.333333
# [2,] 3.333333
# [3,] 4.000000
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment