繁体   English   中英

使用data.table包或其他解决方案子集和重新组合数据帧[R]

[英]Subset and recombine dataframes using data.table package or other solutions [R]

我对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 )!

先感谢您。

抱歉英语不好。

这在data.table是不可能的。 这是FR#203的实施。 您可以尝试打包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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM