3

I would like to take the mean of the two vectors below and store the value in vector B2. Note that I am trying to take the mean value by ROW.

When I use:

B2 <-mean(Macro$X1372C,Macro$X5244C)

I get the error: Error in mean.default(Macro$X1372C, Macro$X5244C) : 'trim' must be numeric of length one. What code should I be using?

enter image description here

The mean vector would look like:

Mean

2.960409952

3.012362779

3.920078183

3.286110877

3.994996196

3.916488088

5.071798314

3.745693115

4.852409799

4.438490606

5.256816758

4.174125673

5.076089227

4.532386721

ZJAY
  • 2,517
  • 9
  • 32
  • 51

2 Answers2

8

You want to use rowMeans(), which produces a vector of the mean of several columns for each row. The input must be an array (i.e., matrix) or data frame.

The code you want is:

 B2 <-rowMeans(cbind(Macro$X1372C,Macro$X5244C))

cbind() puts the two vectors into an array.

Noah
  • 3,437
  • 1
  • 11
  • 27
  • 2
    No need for `cbind`- just `rowMeans(Macro[c("X1372C", "X5244C")])` will do it. – thelatemail Nov 21 '16 at 02:10
  • Totally right. I was imagining a scenario where the vectors were not part of a data frame, but if they are then what you posted is cleaner. – Noah Nov 25 '16 at 05:35
0

We can also do

Reduce(`+`, Macro[c("X1372C", "X5244C")])/2
akrun
  • 874,273
  • 37
  • 540
  • 662