1

here is my code :

m.v <- c("A", "AGG", "A" ,"G", "GA")
count <- 0
for(i in 1: 5){
  if(m.v[i] == "A"|"G"){
    count <- count+1
  }
}

I received the error and I know if(m.v[i] == "A"|"G") is not true because "A" and "G" aren't numeric values, but how can I solve this error?

zahra abdi
  • 307
  • 2
  • 7

2 Answers2

2

You can use %in% instead:

m.v <- c("A", "AGG", "A" ,"G", "GA")
count <- 0
for(i in 1: 5){
  if(m.v[i] %in% c("A", "G")){
    count <- count+1
  }
}
count
[1] 3
Anoushiravan R
  • 21,622
  • 3
  • 18
  • 41
2

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).

r2evans
  • 141,215
  • 6
  • 77
  • 149