2

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?

KeshetE
  • 385
  • 2
  • 5
  • 17
  • Simply `locations[searchfor, V3]` or `locations[.(searchfor), V3]` (to be explicit that you're using the binary search feature). – Arun Jan 12 '15 at 09:22
  • This is a big step forward (Thanks @Arun!), but not quite what I need. The final result should be a list of the found values in V3. I'll add this info to the original question. – KeshetE Jan 12 '15 at 09:28
  • You might find the first half of [this post](http://stackoverflow.com/a/27543075/559784) quite useful in understanding subset/joins in data.table. – Arun Jan 12 '15 at 09:28

1 Answers1

1

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
Arun
  • 116,683
  • 26
  • 284
  • 387
shadow
  • 21,823
  • 4
  • 63
  • 77
  • I removed the `rbind` part, and added output results. Hope okay. If not, please feel free to rewind. – Arun Jan 12 '15 at 09:33