Anirudh Murali Anirudh Murali - 1 year ago 51
R Question

R: How to make sapply calculate mean over rows?

I have a dataset like this

> df
a b c d
1 0.15447394 -0.30926550 -0.008613548 -0.7498640
2 -0.19659661 -0.36732210 0.392225112 -0.1035452
3 0.29479910 -0.38156592 -0.329859865 -1.5651672
4 -0.08113478 -1.44865222 -0.812899295 1.5357360
5 -1.09776659 1.17991490 -1.697510447 -0.7703074
6 0.57770785 -1.26403177 -2.212101953 -1.5634655
7 -1.10261224 -0.76119042 -1.025950267 0.8257326
8 1.30880251 0.39814600 0.533489895 0.4268401
9 -0.21925337 0.13862706 0.782090900 0.2611366
10 -0.40633136 -0.01146429 -0.038013060 -0.8353192


I now want to calculate the mean along the rows, however when I use sapply, I get the following result

> sapply(df, mean)
a b c d
-0.07679115 -0.28268043 -0.44171425 -0.25382231


How to force sapply to perform the mean function along the rows?

Answer Source

You can also use apply:

apply(df, 1, mean)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download