0

I have the following data set:

library(data.table)

dt1 <- data.table(Activity1 = c("A","A","B","B","C","C"),
                  Activity2 = c("B","C","A","C","A","B"),
                  participants = c(12, 22, 4, 20, 3, 31))

# OUTPUT (dt1)
# Activity1 Activity2 participants
# 1:         A         B           12
# 2:         A         C           22
# 3:         B         A            4
# 4:         B         C           20
# 5:         C         A            3
# 6:         C         B           31

I am attempting to find all the unique combinations of Activity1 and Activity2 such that I would end up with a dataset looking like the following (that sums the potential participants):

# DESIRED Dataset
#    Activity1 Activity2 participants
# 1:         A         B           16
# 2:         A         C           25
# 4:         B         C           51

I am still relatively new to R and would appreciate any quidance. Thanks in advance.

Dan
  • 2,625
  • 5
  • 27
  • 42
  • In addition to the options at the duplicated question, you can also try `pmin` and `pmax`, like: `dt1[, list(participants = sum(participants)), by = list(pmin(Activity1, Activity2), pmax(Activity1, Activity2))]`. – A5C1D2H2I1M1N2O1R2T1 Oct 19 '15 at 03:42
  • @AnandaMahto - I don't think that data.table solution over at that duplicate works. The `pmin` and `pmax` are necessary aren't they? – thelatemail Oct 19 '15 at 04:10
  • 2
    @thelatemail - I thought that too, but it turns out you've got to run akrun's first two lines to adjust the data frame first, before running `setDT(df)[...]` – Rich Scriven Oct 19 '15 at 04:11

0 Answers0