OneBite.Dev - Coding blog in a bite size

search for a specific element in an array in R

Code snippet on how to search for a specific element in an array in R

array <- c("a","b","d","c","e")

element <- "d"

pos <- which(array == element)

This code searches for the element “d” in the array [“a”,“b”,“d”,“c”,“e”]. The first line saves this array to a variable called “array”. The second line sets a variable called “element”, and sets it to the value “d”. The third line uses the built-in R function “which()” to search for the elements in the array that match the value stored in the “element” variable, and stores the result to a variable called “pos”. If a match is found, the position of the element in the array is returned.

r