Reputation: 177
> 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
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
f <- structure(c("A", "B", "B", "B", "B", "B", "A", "B", "C"),
.Dim = c(3L, 3L))
Upvotes: 2
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