Search code examples
rcountinteractionkey-pair

Counting pairs in R


I have a dataset of 3 columns with Column 1 being ID(NOT UNIQUE) AND COLUMNS 2 AND 3 being a positive and negative value associated with the id respectively. I am new to R and just trying to figure out how to count the number of pairs of values associated with each id. The table and unique function is not helping since I have to count the pairs. Thanks!


Solution

  • with data.table package

    library(data.table)
    tdata[, list(paircount = .N) , by = c("ID","COLUMN2","COLUMN3")]
    

    EDIT:

    Based on Michael's feedback, I may have misunderstood the question.

    tdata[, list(paircount = nrow((unique(.SD)))), by = "ID"]
    

    should get you what you need.