【问题标题】:Subset and recombine dataframes using data.table package or other solutions [R]使用 data.table 包或其他解决方案 [R] 对数据帧进行子集和重组
【发布时间】:2012-06-22 13:31:34
【问题描述】:

我对 R 很陌生,并且对使用变量之一的范围值在两个数据帧之间进行子集和重组有疑问。所以我有两个这样的数据框:

        x         y                         
 [1,] 79.00     19.63
 [2,] 79.01     19.58
 [3,] 79.02     19.57
 [4,] 79.03     19.58
 [5,] 79.04     19.60
 [6,] 79.05     19.65
 [7,] 79.06     19.67
 [8,] 79.07     19.70
 [9,] 79.08     19.67
[10,] 79.09     19.72

          id        min_x  max_x
[1,] 7G005-1010-10  79.01  79.06  
[2,] 7G100-0001-10  79.02  79.09
[3,] 8S010-1201-10  79.06  79.09

我的目的是像这样将两者结合起来:

     id           x       y
7G005-1010-10   79,01   19,58
7G005-1010-10   79,02   19,57
7G005-1010-10   79,03   19,58
7G005-1010-10   79,04   19,6
7G005-1010-10   79,05   19,65
7G005-1010-10   79,06   19,7
7G100-0001-10   79,02   19,57
     ...         ...     ...

正如您在我的数据帧的输出中看到的那样,我尝试使用 data.table 包来找到解决问题的方法。

好吧,如果有人能告诉我如何处理它(有或没有data.table)!

提前谢谢你。

对不起英语不好。

【问题讨论】:

  • 那么,你想根据 x 的范围来获取 id 吗?如果这就是你想要的,那么范围就会重叠!第一个 id 与第二个重叠,第二个也与第三个重叠。你是怎么处理的?
  • 感谢您提出非常明确的问题,包括输入和所需输出!这很棒。 :)
  • 使用data.table版本>=v1.9.8(2016年11月25日发布到CRAN),可以使用DT1[DT2, on=.(x>=min_x, x<=max_x), nomatch=0L, .(id, x=x.x, y=x.y)]执行非等连接

标签: r data.table


【解决方案1】:

这在data.table 中是不可能的。这是FR#203 来实现的。你可以试试 package xts 因为我认为有这个操作。

data.table 中一种又长又笨重的方式(未经测试)如下。假设您的第一个表是P,第二个包含范围的表是R

setkey(P,x)
# sort by x and mark as sorted so future queries can use binary search on P

from = P[J(R$min_x),which=TRUE]
# Lookup each min_x in the key of P, returning the location. J stands for Join.

to = P[J(R$max_x),which=TRUE]
# Lookup each max_x in the key of P, returning the location.

len = to-from+1
# vectorized for each item the length to[i]-from[i]+1

i = unlist(mapply("seq.int",from,to,SIMPLIFY=FALSE))
# for each item the sequence from[i]:to[i], then concat them all into one vector

cbind(rep(R$id,len), P[i])
# use len to expand the items of R to match what they match to in P

【讨论】:

  • 抱歉耽搁了,非常感谢您的建议。我会尽快尝试的。再次感谢您
  • 我尝试了我们的代码,但遇到了问题。我使用与我的帖子类似的 data.table(如第一个)。当我使用 setkey 函数“Erreur dans setkeyv (P,x) 运行代码时出现此消息:无法将列 'x' 强制转换为整数而不会丢失小数数据。”我查找了 data.table 包的手册,但我无法弄清楚。好吧,如果你能启发我。谢谢美人!最好的问候。
  • @mat 您需要从 R-Forge 存储库安装升级到 v1.8.1。抱歉,我应该提到这一点。按照主页上的链接。允许在键中使用浮点(“数字”)是 v1.8.1 中的新功能。查看最近的演示文稿here
  • 非常感谢您的提示,您的代码完美运行!我不想利用你的好意,但你能解释一下你的代码吗?我不明白所有的微妙之处。正如我所说,我是 R 的新手,我想提高我在这个领域的知识。再一次,非常感谢您的回答以及 data.table 这个出色的软件包。最好的问候
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-10-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多