3

I have a sample dataset. My objective is to keep any records whose user_id and plan_id occur more than once. I understand that you can count the frequency of a variable in a column with

n_occur <- data.frame(table(test$user_id))

But how would one count the frequency of variables in two columns and then filter the original dataset by those that occur more than once? For example, here is my test dataset:

> test
   user_id plan_id hour
1        1      10    2
2        2      10    4
3        3      20   23
4        4      20   12
5        5      10    8
6        1      10   10
7        5      20    6
8        1      20    5
9        1      20   18
10       5      10    7
11       1      30    6

And here is the intended output:

> output
  user_id plan_id hour
1       1      10    2
2       5      10    8
3       1      10   10
4       1      20    5
5       1      20    8
6       5      10   17

and the data:

> dput(test)
structure(list(user_id = c(1, 2, 3, 4, 5, 1, 5, 1, 1, 5, 1), 
    plan_id = c(10, 10, 20, 20, 10, 10, 20, 20, 20, 10, 30), 
    hour = c(2, 4, 23, 12, 8, 10, 6, 5, 18, 7, 6)), .Names = c("user_id", 
"plan_id", "hour"), row.names = c(NA, 11L), class = "data.frame")

Any suggestions would be appreciated!

1
  • this is not a duplicate because it offers a base R solution Sep 13, 2017 at 22:37

1 Answer 1

6

You can use duplicated to check the id columns from the beginning and from the end, if either returns TRUE, the row appears more than once; Then you can use the returned logical vector to subset the data frame:

ids <- df[c('user_id', 'plan_id')]
df[duplicated(ids) | duplicated(ids, fromLast = TRUE),]

#   user_id plan_id hour
#1        1      10    2
#5        5      10    8
#6        1      10   10
#8        1      20    5
#9        1      20   18
#10       5      10    7

Not the answer you're looking for? Browse other questions tagged or ask your own question.