Last active
August 29, 2015 14:10
-
-
Save karawoo/51d23dc7ac604d8ce1ea to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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