title: Second Most Common Element in Each Row
body: <p>I have this dataset in R:</p>
  <pre><code>library(stringr)
  
      set.seed(999)
  
    col1 = sample.int(5, 100, replace = TRUE)
      col2 = sample.int(5, 100, replace = TRUE)
      col3 = sample.int(5, 100, replace = TRUE)
      col4 = sample.int(5, 100, replace = TRUE)
      col5 = sample.int(5, 100, replace = TRUE)
      col6 = sample.int(5, 100, replace = TRUE)
      col7 = sample.int(5, 100, replace = TRUE)
      col8 = sample.int(5, 100, replace = TRUE)
      col9 = sample.int(5, 100, replace = TRUE)
      col10 = sample.int(5, 100, replace = TRUE)
      
    
      d = data.frame(id = 1:10, seq =  c(paste(col1, collapse = &quot;&quot;),  paste(col2, collapse = &quot;&quot;),  paste(col3, collapse = &quot;&quot;),  paste(col4, collapse = &quot;&quot;),  paste(col5, collapse = &quot;&quot;),  paste(col6, collapse = &quot;&quot;),  paste(col7, collapse = &quot;&quot;),  paste(col8, collapse = &quot;&quot;),  paste(col9, collapse = &quot;&quot;), paste(col10, collapse = &quot;&quot;)))
  </code></pre>
  <p>For each row, I would like to create new variables:</p>
  <ul>
  <li>d$most_common: the most common element in each row</li>
  <li>d$second_most_common: the second most common element in each row</li>
  <li>d$third_most_common: the third most common element in each row</li>
  </ul>
  <p>I tried to do this with the following function (<a href="https://stackoverflow.com/questions/19982938/find-the-most-frequent-value-by-row">Find the most frequent value by row</a>):</p>
  <pre><code>rowMode &lt;- function(x, ties = NULL, include.na = FALSE) {
    # input checks data
    if ( !(is.matrix(x) | is.data.frame(x)) ) {
      stop(&quot;Your data is not a matrix or a data.frame.&quot;)
    }
    # input checks ties method
    if ( !is.null(ties) &amp;&amp; !(ties %in% c(&quot;random&quot;, &quot;first&quot;, &quot;last&quot;)) ) {
      stop(&quot;Your ties method is not one of 'random', 'first' or 'last'.&quot;)
    }
    # set ties method to 'random' if not specified
    if ( is.null(ties) ) ties &lt;- &quot;random&quot;
    
    # create row frequency table
    rft &lt;- table(c(row(x)), unlist(x), useNA = c(&quot;no&quot;,&quot;ifany&quot;)[1L + include.na])
    
    # get the mode for each row
    colnames(rft)[max.col(rft, ties.method = ties)]
  }
  
  rowMode(d[1,1])
  </code></pre>
  <p>This gave me an error:</p>
  <pre><code>Error in rowMode(d[1, 1]) : Your data is not a matrix or a data.frame.
  </code></pre>
  <p>Which is a bit confusing, seeing as &quot;d&quot; is a data.frame.</p>
  <ul>
  <li>Is there an easier way to do this?</li>
  </ul>
  <p>Thank you!</p>