So, I've been learning the nuances of data.table for approximately a week. I am currently practicing on the mtcars dataframe. Converted into a data table as follows:
dt<-data.table(mtcars)
I want to subset rows where disp>300 and wt<5. I can do that in 'i' as follows:
dt[disp>300 & wt<5]
mpg cyl disp hp drat wt qsec vs AM gear carb
1: 18.7 8 360 175 3.15 3.440 17.02 0 0 3 2
2: 14.3 8 360 245 3.21 3.570 15.84 0 0 3 4
3: 15.5 8 318 150 2.76 3.520 16.87 0 0 3 2
4: 15.2 8 304 150 3.15 3.435 17.30 0 0 3 2
5: 13.3 8 350 245 3.73 3.840 15.41 0 0 3 4
6: 19.2 8 400 175 3.08 3.845 17.05 0 0 3 2
7: 15.8 8 351 264 4.22 3.170 14.50 0 1 5 4
8: 15.0 8 301 335 3.54 3.570 14.60 0 1 5 8
However, I'm a bit obsessed with keys right now, so I was trying to do the same using keys.
setkeyv(dt,c('disp','wt'))
dt[.(>300,<5)]
This gives an error message as: Error: unexpected '>' in "dt[.(>"
I tried another method(this didn't require key, so I removed them) which too gave the same error.
dt[.(>300,<5),on=.('disp','wt')]
Error: unexpected '>' in "dt[.(>"
Although I can perform the following without problems as they don't have a logical operator:
Using keys: dt[.(145,2.77)]
Without using keys: dt[.(145,2.77),on=c('disp','wt')]
Hence my question is: How to subset rows using key method and also using on(doesn't require key) when subset criteria has a logical operator(eg. >,<,>=,<=)?
Thanks in advance to the wonderful community.