OneBite.Dev - Coding blog in a bite size

count the number of occurrences of a specific element in an array in R

Code snippet on how to count the number of occurrences of a specific element in an array in R

  count = 0
  for(element in array){
    if (element == "specific_element") {
      count = count + 1
    }
  }

This piece of code allows us to count the number of occurrences of a specific element in an array. The first step is to create a variable called “count” and set its value to 0. This will be used to track the number of occurrences of the element. Next is a loop that will go through each element in the array one by one. Whenever the element being processed is equal to the one we are looking for, we will add one to the “count” variable. We will keep doing this until we have gone through all elements in the array. At the end, the “count” variable will contain the total number of times the specific element has occurred in the array.

r