Count most frequent word in row by R
<p>There is a table shown below </p>

<pre><code>   Name     Mon    Tue     Wed    Thu     Fri    Sat    Sun

1 John     Apple  Orange  Apple  Banana  Apple  Apple  Orange
2 Ricky    Banana Apple   Banana Banana  Banana Banana Apple
3 Alex     Apple  Orange  Orange Apple   Apple  Orange Orange
4 Robbin   Apple  Apple   Apple  Apple   Apple  Banana Banana
5 Sunny    Banana Banana  Apple  Apple   Apple  Banana Banana
</code></pre>

<p>So , I want to count the most frequent Fruit for each person and add those value in new column.   </p>

<p>For example.</p>

<pre><code>   Name     Mon    Tue     Wed    Thu     Fri    Sat    Sun      Max_Acc  Count

1 John     Apple  Orange  Apple  Banana  Apple  Apple  Orange     Apple       4
2 Ricky    Banana Apple   Banana Banana  Banana Banana Apple      Banana      5
3 Alex     Apple  Orange  Orange Apple   Apple  Orange Orange     Orange      4
4 Robbin   Apple  Apple   Apple  Apple   Apple  Banana Banana     Apple       5
5 Sunny    Banana Banana  Apple  Apple   Apple  Banana Banana     Banana      4
</code></pre>

<p>I am facing problem in finding rows. I can find Frequency in column by using <code>table()</code> function.</p>

<pre><code>&gt;table(df$Mon)

 Apple  Banana
  3      2
</code></pre>

<p>But here i want name of most frequent fruit in new column.     </p>

<p>Another approach would be to loop over all unique fruits as follows</p>

<pre><code>fruits_unique &lt;- unique(unlist(dat[-1]))
occurence &lt;- sapply(fruits_unique, function(x) rowSums(dat[,-1] == x)) 
# Using this data to create the resulting columns
ind &lt;- apply(occurence,1,which.max)
dat$Names &lt;- fruits_unique[ind]
dat$count &lt;- occurence[cbind(seq_along(ind), ind)]
</code></pre>

<p>Result:</p>

<pre><code>    Name    Mon    Tue    Wed    Thu    Fri    Sat    Sun  Names Count
1   John  Apple Orange  Apple Banana  Apple  Apple Orange  Apple     4
2  Ricky Banana  Apple Banana Banana Banana Banana  Apple Banana     5
3   Alex  Apple Orange Orange  Apple  Apple Orange Orange Orange     4
4 Robbin  Apple  Apple  Apple  Apple  Apple Banana Banana  Apple     5
5  Sunny Banana Banana  Apple  Apple  Apple Banana Banana Banana     4
</code></pre>

python pyspark rpy2 word-frequency