2012-06-22 60 views
3

我很新的R和有一個關於子集的問題和使用該變量中的一個的範圍內值的兩個數據幀之間的重組。所以,我有我的兩個dataframes這樣的:子集和重組dataframes使用data.table包或其他溶液[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)!

預先感謝您。

對不起英文不好。

+0

所以,你試圖根據x的範圍落入id?如果這就是你想要的那麼範圍重疊!第一個id與第二個id重疊,第二個id與第三個重疊。你如何處理這個問題? –

+0

謝謝你輸入和期望的輸出非常明確的問題!這很棒。 :) – Ashe

回答

4

這是不可能的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 
+1

+1爲您自己的SO項目提供支持。 –

+0

對不起,我們非常感謝您的建議。我會盡快嘗試。 再次感謝您 – mat

+0

我想我們的代碼,但我有一個問題。我對我的文章使用了類似的data.table(比如第一個)。當我使用setkey函數運行代碼時,我有這條消息 'Erreur dans setkeyv(P,x): 列'x'不能被強制爲整數而不丟失小數數據。 我找了data.table包的手冊,但我無法弄清楚。那麼,如果你能啓發我。 Merci beaucoup! 此致敬禮。 – mat