I have a matrix in R, here is a small example:
set.seed(1)
n.columns<-6
mat <- matrix(, nrow = 5, ncol = n.columns)
for(column in 1:n.columns){
mat[, column] <- sample(1:10,5)
}
mat
The matrix looks like this:
[,1] [,2] [,3] [,4] [,5] [,6]
[1,] 3 9 3 5 10 4
[2,] 4 10 2 7 2 1
[3,] 5 6 6 8 6 10
[4,] 7 5 10 3 1 7
[5,] 2 1 5 10 9 3
I also have a vector v
of integers, v<-c(1,3,6)
, whose elements could theoretically appear in the matrix mat
above.
What I am looking for is an overview of the number of times that each element in v
appears in mat
per column. For the current example this overview is
1: 0 1 0 0 1 1
3: 1 0 1 1 0 1
6: 0 1 1 0 1 0
It is fairly straightforward to do this using for
-loops and if
-statements, but this solution is not very pretty.
Is there a professional way to do this?
One option using sapply
:
t(sapply(v, function(a) colSums(mat==a)))
# [,1] [,2] [,3] [,4] [,5] [,6]
#[1,] 0 1 0 0 1 1
#[2,] 1 0 1 1 0 1
#[3,] 0 1 1 0 1 0