R - select rows where at least X columns meet the condition

I am trying to select those rows where at least 4 of the columns have the same value. So far, I have tried applying the function and I can get the lines where any line matches.

team.composition[apply(team.composition, 1, function(X) any(as.numeric(X) == 1)),]

      

This is an example of my table

member.1 member.2 member.3 member.4 member.5
   1         3        8       5        3
   2         3        2       2        2
   7         4        8       8        3
   1         8        8       8        8

      

I would like to return the second row (2,3,2,2,2) and the fourth row (1,8,8,8,8).

Any suggestions? Thanks to

+3


source to share


1 answer


Try

df1[apply(df1, 1,function(x) any(table(x)>=4)),]

      



or

 library(reshape2)
 df1[!!rowSums(table(melt(as.matrix(df1))[-2])>=4),]

      

+5


source







All Articles