0

Similarly to the example on this page, I wan to sum the values in a column and divide it by the count of another. For example in the following code:

A <- c(1,1,2,2)
B <- c(0.2, 0.3, 1, 0.5)
M <- data.frame(A,B)
M

  A   B
1 1 0.2
2 1 0.3
3 2 1.0
4 2 0.5

I need to sum(B) with ID 1 and divide it by count(A) with ID 1. Similarly for ID 2.

The result should be as follows:

A.1 <- c(1, 2)
B.1 <- c((0.2+0.3)/2, (1+0.5)/2)
M.1 <- cbind(A.1, B.1)
M.1

     A.1  B.1
[1,]   1 0.25
[2,]   2 0.75

Any ideas on how to go about doing that?

Community
  • 1
  • 1
Selrac
  • 2,203
  • 9
  • 41
  • 84
  • 1
    You want the average of B by ID? `aggregate(B ~ A, data = M, FUN = mean)` – bouncyball Feb 10 '17 at 14:04
  • Another related post: http://stackoverflow.com/questions/21982987/mean-per-group-in-a-data-frame – zx8754 Feb 10 '17 at 14:12
  • @zx8754 It is easy to direct it to a dupe when the wordings are clear. But, based on OP's description, some of us painstakingly did the difficult task of parsing the words and directing it to simple functions. So, the dvs are not justified,.. Anyway.. BTW, your dupe link is not correct as it is for multiple columns, multiple functions etc. – akrun Feb 10 '17 at 14:19
  • 1
    @akrun This post at most deserves a comment with direction towards "mean", which boucyball rightly did, once we knew it was "group by mean" post, it is a dupe, there was no need spamming with easy answers. – zx8754 Feb 10 '17 at 14:22
  • @akrun feel free to re-hammer with above link or any other more relevant post. – zx8754 Feb 10 '17 at 14:24
  • @zx8754 Your related post looks promising. Anyway, it's okay – akrun Feb 10 '17 at 14:27
  • Thanks bouncyball, that does the trick!! Nice. – Selrac Feb 10 '17 at 15:21

1 Answers1

-1

Without using external libraries, and only the most basic functions.

mat <- matrix(NA,0,2)
for (v in unique(M$A)) {
  m <- mean(M[which(M$A == v),'B'])
  mat <- rbind(mat,c(v,m))
}
Rodrigo
  • 4,706
  • 6
  • 51
  • 94