No need for a for
loop:
sum(m.v %in% c("A","G"))
# [1] 3
R really benefits from vectorizing calculations. In this case, R (internally) will check each of m.v
's values against the vector c("A","G")
, but externally from the user perspective, we just need to worry about the vector as a whole. Without sum
, it returns a logical
vector:
m.v %in% c("A","G")
# [1] TRUE FALSE TRUE TRUE FALSE
With that, when we do math operations on logicals, it silently casts them as integer
, which sum up nicely to the intended 3
.
Not every operation in R can be done as a vector-as-a-whole, but when one can do that, one benefits in both readability (subjective) and performance (relevant for larger datasets).