BillyJean
BillyJean

Reputation: 1587

Find frequency of vector elements in a matrix

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?

Upvotes: 1

Views: 967

Answers (3)

d.b
d.b

Reputation: 32558

Using sapply on data.frame iterates over columns.

setNames(object = as.data.frame(sapply(v, function(a)
         sapply(as.data.frame(mat), function(b)
                             sum(a %in% b)))), nm = v)
#   1 3 6
#V1 0 1 0
#V2 1 0 1
#V3 0 1 1
#V4 0 1 0
#V5 1 0 1
#V6 1 1 0

Upvotes: 1

mt1022
mt1022

Reputation: 17299

Using table:

table(mat[mat %in% v], col(mat)[mat %in% v])

#   1 2 3 4 5 6
# 1 0 1 0 0 1 1
# 3 1 0 1 1 0 1
# 6 0 1 1 0 1 0

A drawback is a column with all values not in v will not be reported.

Upvotes: 1

989
989

Reputation: 12935

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

Upvotes: 1

Related Questions