[英]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. 我试图将下面的行(r1)分成3个长的段,然后平均第1行和第2行。我试图使用dplyr软件包只是因为我想学习它。 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. dplyr软件包主要用于对数据帧进行分组操作。 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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.