Reputation:
now I am exampling a matrix but should be the same as a data frame imagine we have three data frame
Mat1<- matrix(rexp(3, rate=.1), ncol=3, nrow=5)
Mat2<- matrix(rexp(3, rate=.1), ncol=3, nrow=5)
Mat3<- matrix(rexp(3, rate=.1), ncol=3, nrow=5)
I know if I want to plus each and all cells and make one data frame out of it, I can simply do
M <- Mat1+Mat2+Mat3
but instead I want to take the mean of each three cells and not the plus of each three cells, how can I do that ?
Upvotes: 2
Views: 102
Reputation: 887223
If there are many matrices, you could use Reduce
after placing the matrices in a list. Get the +
of the elements and divide it by the length of the list.
lst <- mget(paste0('Mat', 1:3))
Reduce(`+`, lst)/length(lst)
Same way, you can do
Reduce(`+`, lst)
In general, if the object names follow a specific pattern, this would be useful. But, if the matrices are `xy13542xy', 'z62', 'Ak912f', etc, without much pattern, then we need to construct the list manually
lst <- list(xy13542xy, z62, Ak912f)
Suppose, if there is a pattern i.e. s1, m1, d1
etc
lst <- mget(ls(pattern='^[a-z]+\\d+'))
Upvotes: 1
Reputation:
If I understood you correctly, you can just do this:
(Mat1+Mat2+Mat3)/3
Upvotes: 1