Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R data.table subsetting on multiple conditions.

Tags:

r

data.table

With the below data set, how do I write a data.table call that subsets this table and returns all customer ID's and associated orders for that customer IF that customer has ever purchased SKU 1?

Expected result should return a table that excludes cid 3 and 5 on that condition and every row for customers matching sku==1.

I am getting stuck as I don't know how to write a "contains" statement, == literal returns only sku's matching condition... I am sure there is a better way..

library("data.table")    
df<-data.frame(cid=c(1,1,1,1,1,2,2,2,2,2,3,4,5,5,6,6),
    order=c(1,1,1,2,3,4,4,4,5,5,6,7,8,8,9,9),
    sku=c(1,2,3,2,3,1,2,3,1,3,2,1,2,3,1,2))

    dt=as.data.table(df)
like image 729
digdeep Avatar asked Nov 20 '13 03:11

digdeep


1 Answers

This is similar to a previous answer, but here the subsetting works in a more data.table like manner.

First, lets take the cids that meet our condition:

matching_cids = dt[sku==1, cid]

the %in% operator allows us to filter to just those items that are contained in the list. so, using the above:

dt[cid %in% matching_cids]

or on one line:

> dt[cid %in% dt[sku==1, cid]]
     cid order sku
  1:   1     1   1
  2:   1     1   2
  3:   1     1   3
  4:   1     2   2
  5:   1     3   3
  6:   2     4   1
  7:   2     4   2
  8:   2     4   3
  9:   2     5   1
 10:   2     5   3
 11:   4     7   1
 12:   6     9   1
 13:   6     9   2
like image 112
Peter Fine Avatar answered Nov 09 '22 01:11

Peter Fine