Count unique elements in data frame row and return one with maximum occurrence

dataframe, r, vector

Solution

You can use `apply` to use `table` function on every row of dataframe.

df <- read.table(textConnection("a a a b b b b\nc v f w w r t\ns s d f b b b"), header = F)

df$result <- apply(df, 1, function(x) names(table(x))[which.max(table(x))])

df
##   V1 V2 V3 V4 V5 V6 V7 result
## 1  a  a  a  b  b  b  b      b
## 2  c  v  f  w  w  r  t      w
## 3  s  s  d  f  b  b  b      b

Problem

Is it possible to count unique elements in data frame row and return one with maximum occurrence and as result form the vector. ``` example: a a a b b b b -> b c v f w w r t -> w s s d f b b b -> b ```

Original source

Related problems