Debjyoti
Debjyoti

Reputation: 177

How to store number of specific characters from a matrix into another vector in R

> f
[,1] [,2] [,3] 
[1,] "A"  "B"  "A"
[2,] "B"  "B"  "B"
[3,] "B"  "B"  "C"

Let's consider that I have generated a matrix like the one above. I want to store the number of specific characters (eg: "B") from the above matrix into a separate vector.

I am expecting a result like this:

f_B
[1] 2 3 1

f_B is another vector

Upvotes: 0

Views: 37

Answers (2)

akrun
akrun

Reputation: 887431

We can use colSums on the logical matrix

f_B <- colSums(f == "B")
f_B
#[1] 2 3 1

If we need to get the frequency of each unique element for each of the columns

table(f, col(f))      
#f   1 2 3
#  A 1 0 1
#  B 2 3 1
#  C 0 0 1

data

f <- structure(c("A", "B", "B", "B", "B", "B", "A", "B", "C"), 
  .Dim = c(3L, 3L))

Upvotes: 2

MKR
MKR

Reputation: 20095

You can have vector for all elements using sapply on unique elements of matrix as:

t(sapply(unique(as.vector(f)),function(x)colSums(f==x)))

#   [,1] [,2] [,3]
# A    1    0    1
# B    2    3    1
# C    0    0    1

Note: The above solution is sight extension to the answer provided by @akrun

Data:

f <- matrix(data = c("A","B","A","B","B","B","B","B","C"), byrow = TRUE, nrow = 3)

Upvotes: 2

Related Questions