1

Possible duplicate on SO: Computing a new variable using conditions of an existing data frame

I am trying to create a vector (e.g. z) from the group means. The vector will have a length equal to the number of rows of the original data frame from where the group mean was created and each element of the vector z will correspond to the group member.

For example,

A      mean of group A
C      mean of group c
F      mean of group F
C      mean of group C

etc.

Any help will be appreciated.

Community
  • 1
  • 1
Amirul Islam
  • 407
  • 1
  • 6
  • 15
  • [Read this](http://stackoverflow.com/q/5963269) in order to learn how to make a good question. You have to put some more effort on explaining what have you done so far, give some sample data and explaine what is your desired output. Good questions are more likely to be answered. – Jilber Urbina May 14 '13 at 16:31

3 Answers3

4

Sounds like you need the function ave

try looking at

?ave

e.g. try

ave(InsectSprays$count,InsectSprays$spray)

(InsectSprays comes with R, that should work as it stands) or

with(InsectSprays, ave(count,spray))

So do the equivalent with your data and assign it to z

Here's what it does (try pasting the first two lines in and then examining InSp):

 InSp <- InsectSprays
 InSp$ave <- with(InSp, ave(count,spray))
 head(InSp,15)
   count spray      ave
1     10     A 14.50000
2      7     A 14.50000
3     20     A 14.50000
4     14     A 14.50000
5     14     A 14.50000
6     12     A 14.50000
7     10     A 14.50000
8     23     A 14.50000
9     17     A 14.50000
10    20     A 14.50000
11    14     A 14.50000
12    13     A 14.50000
13    11     B 15.33333
14    17     B 15.33333
15    21     B 15.33333

The function ave has many other uses because you can supply it a function as an argument (and then instead of calculating means it will use whatever other function by group that you wish); for a particularly subtle use of it, see this answer.

Community
  • 1
  • 1
Glen_b
  • 7,883
  • 2
  • 37
  • 48
1

You could use rowMeans as described here:

Calculate row means on subset of columns

data <- matrix(c(1:12),nrow=3)

z <- rowMeans(data)

data
     [,1] [,2] [,3] [,4]
[1,]    1    4    7   10
[2,]    2    5    8   11
[3,]    3    6    9   12

z
[1] 5.5 6.5 7.5
Community
  • 1
  • 1
timcdlucas
  • 1,334
  • 8
  • 20
  • I think the OP is looking for `ave` and if so, your answer is not the correct one since it is not taking into account the gruops as the OP want. – Jilber Urbina May 14 '13 at 16:28
0

I don't quite follow how your original data are set up, so it would help to know more about that.

If you have data in rows, and you just want a new vector where each element is the mean of the corresponding row, that can be done easily using R's ?apply function:

X     = matrix(rnorm(100), nrow=10)
means = apply(X, 1, mean)
gung - Reinstate Monica
  • 11,583
  • 7
  • 60
  • 79