find the kth most common element in an array in r

To find the kth most common element in an array in R, we can follow these steps:

  1. Create the array.
  2. Find the frequency of each element in the array using the table function.
  3. Sort the frequency table in descending order using the sort function.
  4. Determine the kth element in the sorted frequency table.
  5. Return the element that corresponds to the determined frequency in the original array.

Here's the R code to implement this algorithm:

main.r
# Create an example array
arr <- c(5, 2, 3, 2, 4, 4, 4, 1, 1)

# Get the frequency of each element
freq_table <- table(arr)

# Sort the frequency table in descending order
sorted_freq_table <- sort(freq_table, decreasing = TRUE)

# Determine the kth most common element
k <- 2
kth_freq <- sorted_freq_table[k]

# Find the element that corresponds to the kth frequency
kth_element <- as.numeric(names(sorted_freq_table)[sorted_freq_table == kth_freq])

# Print the result
kth_element
483 chars
19 lines

In this example, the output is 4 because it is the second most common element in the array after 2.

gistlibby LogSnag