Reputation: 395
I have a data.table with two of its columns (V1,V2) set as a key. A third column contains multiple values.
I have another data.table with pairs I want to search for in the first table key, and return a united list of the lists in V3.
locations<-data.table(c(-159.58,0.2,345.1),c(21.901,22.221,66.5),list(c(10,20),c(11),c(12,33)))
setkey(locations,V1,V2)
searchfor<-data.table(lon=c(-159.58,345.1,11),lat=c(21.901,66.5,0))
The final result should look like this:
[1] 10 20 12 33
The following works when searching for just one item.
locations[.(-159.58,21.901),V3][[1]]
[1] 10 20
I don't know how to generalize this and use the table "searchfor" as source for the searched indices (BTW - the "searchfor" table can be changed to a different format if it makes the solution easier). Also, how do I unite the different values in V3 I'll then (hopefully) receive, into one list?
Upvotes: 2
Views: 1634
Reputation: 22293
You can use the same syntax that you used with a data.table
as an index.
lst <- locations[ .(searchfor), V3]
You probably want to use only the non-null elements. If so, you can directly use nomatch=0L
argument:
locations[ .(searchfor), V3, nomatch=0L]
# [[1]]
# [1] 10 20
#
# [[2]]
# [1] 12 33
This will return a list. If you want to return a vector instead, use the base function unlist()
as follows:
locations[ .(searchfor), unlist(V3), nomatch=0L]
# [1] 10 20 12 33
Upvotes: 1