-3

I've got a data frame with two columns: name and action_id. Names often have multiple action_ids, and action_ids are also associated with multiple names, like so:

name action_id
Bob  1
Bob  2
Bob  3
Tom  2
Tom  1
Bill 1
Bill 3

Here's my problem: I'm trying to index the overlap between the action_ids based on the names. So if a name is associated with two action_ids, and another name is associated with the same two action_ids, the overlap between those two action_ids is 1. For the data above, this function would return an overlap of 1 between action_ids 1 and 2, 1 between 1 and 3, and 0 for other potential overlaps. I'm picturing a data table with all potential action_id overlaps and the instances of those overlaps, like so:

  1 2 3
1 - 0 0 
2 1 - 0
3 1 0 -

I've tried to tackle this by converting the data frame to a data table that indexes all action_ids associated with users, but am having trouble then converting that data table into an action_id-only table as shown above.

I thought of looping through all the data, but I'm dealing with millions of rows -- for/if loops aren't time-efficient enough here, so I'm trying to find a vector-based solution.

5
  • 1
    It would be good to give a specific indication of your entire desired output for this example
    – alexwhan
    Commented Mar 12, 2013 at 1:32
  • @alexwhan they have given their specific desired output for the example, in the paragraph after. Commented Mar 12, 2013 at 1:34
  • I understand, I mean as it will appear, instead of "I'm picturing..." actually showing the data - I'm not trying to be picky, but it generally leads to quicker and more accurate responses.
    – alexwhan
    Commented Mar 12, 2013 at 1:37
  • 1
    What have you tried and what is the format of desired output? Good people here aren't going to write code for you without knowing that you have put in any effort
    – CHP
    Commented Mar 12, 2013 at 2:00
  • Thanks, all. I've updated the question with example output and explanation of progress to-date.
    – T_T
    Commented Mar 12, 2013 at 17:16

1 Answer 1

2

I think this calculates the overlaps in the way you wanted:

overlap = function(df, id1, id2) {
  id_by_name = tapply(df$action_id, df$name, unique)
  ids_in_name = lapply(
    id_by_name,
    function(x) {
      all(c(id1, id2) %in% x)
    }
  )
  overlapping_names = names(ids_in_name)[unlist(ids_in_name)]
  if (length(overlapping_names) >= 2) {
    return(1)
  } else {
    return(0)
  }
}

Output:

> overlap(df, 1, 2)
[1] 1
> overlap(df, 2, 3)
[1] 0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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