user3276768
user3276768

Reputation: 1436

R - Select rows where at least X columns matches condition

I am trying to select those rows where at least 4 of the columns have the same value. So far, I have tried the apply function and I can get the rows where any or every row 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

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

Any suggestions? Thanks

Upvotes: 3

Views: 1396

Answers (1)

akrun
akrun

Reputation: 887098

Try

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

Or

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

Upvotes: 6

Related Questions