简体   繁体   中英

How can I split a dataframe and average across rows using dplyr?

I am trying to split the following row (r1) into segments that are 3 long, then average row 1 and row 2. I am trying to use the dplyr package just because I am trying to learn it. Can someone point me in the right direction?

r1<-rbind(c(1,2,3,4,5,6,7,8,9),c(11,21,31,41,51,61,71,81,91))
colnames(r1)<-c("a","b","c","d","e","f","g","h","i")
library(dplyr)
test<-r1 %>% group_by("a","b","c")

Goal:

avg(1+11),avg(2+21),avg(3+31)
avg(4+41),avg(5+51),avg(6+61)
avg(7+71),avg(8+81),avg(9+91)

The dplyr package is used primarily for grouped operations on data frames. You have a matrix there and it's not really a grouping operation. You just want to rearrange the column means. For that we can do the following.

matrix(colMeans(r1), 3, byrow = TRUE)
#      [,1] [,2] [,3]
# [1,]  6.0 11.5 17.0
# [2,] 22.5 28.0 33.5
# [3,] 39.0 44.5 50.0

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM