I am trying to figure out how I can perform logical operators
when I use indexing in data.table package
in R
?
Following is the example. I make a datatable
named as dt
. and then make the var2
as the key in my datatable
:
> dt = data.table(var1 = rep(LETTERS[1:5],2), var2 = seq(1,20, 2), var3 = ceiling(rnorm(10, 3, 2)))
> dt
var1 var2 var3
1: A 1 5
2: B 3 3
3: C 5 0
4: D 7 6
5: E 9 3
6: A 11 4
7: B 13 2
8: C 15 1
9: D 17 3
10: E 19 7
> setkey(dt, var2)
So now I want to identify all the values in my already defined key (var2)
which are less than 10 ( <10)
. Doing the following tries give me errors
.
> dt[ < 10]
Error: unexpected '<' in "dt[ <"
> dt[ .< 10]
Error in eval(expr, envir, enclos) : object '.' not found
> dt[ .(< 10)]
my expectation would be :
var1 var2 var3
1: A 11 4
2: B 13 2
3: C 15 1
4: D 17 3
5: E 19 7
BTW, I know that just by doing dt[var2 <10]
I will get the result. BUT please consider that I want to get the concept of Indexing in data.table
and understand and know how to do it without calling the key(var2)
in every each of my command!
Any help with explanation is highly appreciated.