Vowels in a matrix in R

Viewed 65

I have a 25x25 matrix which consists of random letters and i want to count the number of vowels in each column. I managed to do it by

    count <- function(x) {
      return(sum(x %in% c("a","e","i","o","u")))}

and write the function in apply(). Is there another way of doing this without using loops or %in% ?

1 Answers

Data

set.seed(1L)
mat <- matrix( sample(letters, size = 625, replace = TRUE), nrow = 25)
vowels <- c('a', 'e', 'i', 'o', 'u')

Code

apply(mat, 2, function(x) length(na.omit(match(x, vowels))))
# [1] 4 8 4 4 2 4 6 5 6 1 5 7 2 5 3 6 6 1 4 5 5 7 5 3 4

# another way without using apply()
mat[] <- match(mat, vowels)
colSums(!is.na(mat))
# [1] 4 8 4 4 2 4 6 5 6 1 5 7 2 5 3 6 6 1 4 5 5 7 5 3 4
Related