简体   繁体   中英

How to use apply function in a filtered matrix column?

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. eg 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 eg (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)

根据更新的帖子,我们可以将分组变量用作第一列

tapply(AllFiltered[,3], AllFiltered[,1], FUN= mean)

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