0

Let's say I have a dataset.

w=c(5,6,7,8)
x=c(1,2,3,4)
y=c(1,2,3,5)
length(y)=4
z=data.frame(w,x,y)

This will return

  w x  y
1 5 1  1
2 6 2  2
3 7 3  3
4 8 4  5

I would like to have a 5th row that averages only row 2 and 3.

  w   x   y
1 5   1   1
2 6   2   2
3 7   3   3
4 8   4   5
5 6.5 2.5 2.5

How would I approach this? There are a lot of examples with rowMeans, but I'm looking to average all columns, and from only specific rows.

strkiky2
  • 79
  • 6

2 Answers2

1

You can use colMeans as :

rows <- c(2, 3)
rbind(z, colMeans(z[rows,]))

#    w   x   y
#1 5.0 1.0 1.0
#2 6.0 2.0 2.0
#3 7.0 3.0 3.0
#4 8.0 4.0 5.0
#5 6.5 2.5 2.5
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213
1

Does this work:

library(dplyr)

z %>% bind_rows(sapply(z[2:3,], mean))
    w   x   y
1 5.0 1.0 1.0
2 6.0 2.0 2.0
3 7.0 3.0 3.0
4 8.0 4.0 5.0
5 6.5 2.5 2.5
Karthik S
  • 11,348
  • 2
  • 11
  • 25