There are lots of question the flirt around this issue, but I haven't been able to find answer to my particular concern. I have a dataframe that has this general format.
dat <- data.frame(V1 = c(1,1,2,1,2,4,5), V2 = c(1,2,1,2,1,5,4), V3 = c('date1','date1','date2','date3','date4','date1','date2'))
dat
V1 V2 V3
1 1 date1
2 1 date1
1 2 date2
1 2 date3
2 1 date4
5 4 date1
4 5 date2
I want to find unique pairs from column 1 and 2 (so that row 2, 3, 4, 5 are all consolidated into a single unique pair) regardless of order (1, 2 = 2, 1). I found this nice code on SO (Unique pairs in R, ignoring order)
colwise <- function(dat) data.frame(unique(cbind(pmin(dat[,1], dat[,2]), pmax(dat[,1], dat[,2]))))
Which works great for pulling out columns 1 and 2.
colwise(dat)
V1 V2
1 1
1 2
4 5
However, I would like to find the unique pairs (as above) but also include the entire first row from the original dataset for each unique pair. In the example above the final output would be
dat
V1 V2 V3
1 1 date1
1 2 date1
4 5 date1
In my actual dataset I have many more columns and several ~1 million rows, though only 100-200 truly unique combinations of column 1 and 2. Additionally, the unique pair columns are not actually columns 1, 2 in my dataset so the ability to specify specific columns to test for uniqueness is important.
Does anyone have some good thoughts for how to modify the colwise function or how to use the resulting set of unique pairs to pull from the original dataframe the first entire row based on that unique pair?
Thank you