Create a matrix with (1) an indicator , (2) a condition and (3) a variable of interest x
z<-rep(1:10,each=10)
set.seed(974); cond=rbinom(100,3,0.5)
set.seed(974) ; x=rnorm(100,1,10)
All<-cbind(z,cond,x) ; All
Using the whole dataset I can compute the quantity of interest with colsums or apply. e.g. Mean per 10 rows.
colSums(matrix(as.numeric(All[,3]), nrow=10))/10
apply(matrix(as.numeric(All[,3]), nrow=10),2,mean)
# Filtered dataset.
AllFiltered<-All[All[,2]==1,]
Now, When I perform the filtering the nrow are not constant e.g. (1,2,3,3). Is there a way to perform the same action as above to every separate group of rows filtered data?
Example of Allfiltered
z cond x
[1,] 1 1 -10.5135290
[2,] 2 1 -10.9883098
[3,] 2 1 12.9269151
[4,] 3 1 5.1725988
[5,] 3 1 -1.5633754
[6,] 3 1 -1.3470068
[7,] 4 1 12.6646369
[8,] 4 1 -9.7694997
[9,] 4 1 4.8618008
Would like to get the mean for every group of rows, where the number of rows after the filtering is not constant and equal to a fixed number (will change depending on the condition filter)