【问题标题】:R data.table - searching for multiple rows by key which is composed of 2 columnsR data.table - 按由 2 列组成的键搜索多行
【发布时间】:2015-01-12 09:14:24
【问题描述】:

我有一个 data.table,其中两列 (V1,V2) 设置为键。第三列包含多个值。

我有另一个 data.table,其中包含我想在第一个表键中搜索的对,并返回 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))

最终的结果应该是这样的:

[1] 10 20 12 33

仅搜索一项时以下工作。

locations[.(-159.58,21.901),V3][[1]]
[1] 10 20

我不知道如何概括这一点并使用表“searchfor”作为搜索索引的源(顺便说一句 - 如果它使解决方案更容易,可以将“searchfor”表更改为不同的格式)。 另外,我如何将 V3 中的不同值合并到一个列表中?

【问题讨论】:

  • 只需 locations[searchfor, V3]locations[.(searchfor), V3](明确表示您正在使用二进制搜索功能)。
  • 这是向前迈出的一大步(感谢@Arun!),但不是我所需要的。最终结果应该是 V3 中找到的值的列表。我会将此信息添加到原始问题中。
  • 您可能会发现this post 的前半部分对于理解 data.table 中的子集/联接非常有用。

标签: r data.table


【解决方案1】:

您可以使用与data.table 相同的语法作为索引。

lst <- locations[ .(searchfor), V3]

您可能只想使用非空元素。如果是这样,您可以直接使用nomatch=0L 参数:

locations[ .(searchfor), V3, nomatch=0L]
# [[1]]
# [1] 10 20
# 
# [[2]]
# [1] 12 33

这将返回一个列表。如果您想返回一个向量,请使用基函数unlist(),如下所示:

locations[ .(searchfor), unlist(V3), nomatch=0L]
# [1] 10 20 12 33

【讨论】:

  • 我删除了rbind 部分,并添加了输出结果。希望没事。如果没有,请随时倒带。
  • 谢谢@Arun,这太完美了。
猜你喜欢
  • 1970-01-01
  • 2021-01-11
  • 2018-04-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-07-23
相关资源
最近更新 更多