2017-07-31 97 views
1

我有一系列我想要合併的數據幀,按順序累加特定元素。對於背景,這些是用於基因組序列數據的單獨分區文件,其參考沿着比對的基因區域(將其想象爲字符串的部分)。我將序列對齊合併在一起,因此需要將分區文件合併在一起,同時保留分區相對位置。儘可能地將這一點儘可能地適應個別分區文件的任何數目和長度是很好的。R按順序合併元素合併數據幀 - 棘手。

的合併和總結需要工作是這樣的:

  1. 第二列元素是前行的第三列元素加一。
  2. 對於第一個數據幀,第三列:第一個元素等於n,第二個元素等於2n,第三個元素是3n,依此類推。
  3. 在新合併的數據幀中,第三列的第一個元素將成爲其值(x)加上前一個數據幀(x +?n)中第三列的最後一個元素。然後將x添加到每行的x +?n,直到數據幀的結尾或新的一個合併爲止。

一個簡單的例子會更好地解釋。

這裏是1區的數據幀:

    V1 V2 V3 
Region_1_Partition_1  1 500 
Region_1_Partition_2 501 1000 
Region_1_Partition_3 1001 1500 

這裏是區域2:

    V1 V2 V3 
Region_2_Partition_1  1 200 
Region_2_Partition_2 201 400 
Region_2_Partition_3 401 600 

最終分區文件需要是這樣的:

    V1 V2 V3 
Region_1_Partition_1  1 500 
Region_1_Partition_2 501 1000 
Region_1_Partition_3 1001 1500 
Region_2_Partition_1 1501 1700 
Region_2_Partition_2 1701 1900 
Region_2_Partition_3 1901 2001 

我猜猜到目前爲止,還有很多完美的解決方案無法解決!

感謝 Ç

回答

1

編輯:對不起,我平時瀏覽data.table()的具體問題,並沒有注意到這個問題是關於數據幀!我相應地更改了我的答案

我會保留「n」作爲列,以便您可以在最終框架中將其放入cumsum()。這我不會被merge而是由rbind()

首先實現「再造」數據

region1 <- data.frame(
    label=c('Region_1_Partition_1', 'Region_1_Partition_2', 
'Region_1_Partition_3'), 
    V4=500 
) 

region1$V3 <- cumsum(region1$V4) 
region1$V2 <- region1$V3 - region1$V4 + 1 
region1[, c('label', 'V2', 'V3')] 

最後一個命令返回

    label V2 V3 
1: Region_1_Partition_1 1 500 
2: Region_1_Partition_2 501 1000 
3: Region_1_Partition_3 1001 1500 

相似的代碼,用V4=200可以給區域2。

現在執行你的組合,

out <- rbind(region1[, c('label', 'V4')], region2[, c('label', 'V4')]) 

out$V3 <- cumsum(out$V4) 
out$V2 <- out$V3 - out$V4 + 1 
out[, c('label', 'V2', 'V3')] 


        label V2 V3 
1: Region_1_Partition_1 1 500 
2: Region_1_Partition_2 501 1000 
3: Region_1_Partition_3 1001 1500 
4: Region_2_Partition_1 1501 1700 
5: Region_2_Partition_2 1701 1900 
6: Region_2_Partition_3 1901 2100 

ANOTHER編輯:如何擴展解決方案,以分區的更大的數字。

我可以在這裏看到兩個挑戰,第一個是需要所有的東西,第二個是需要確定在V4列中使用什麼。

有可能是這樣(像存儲在列表中的所有表,然後壓扁下來,一個表)更有效的方式 - [R。我只會使用for循環。

比方說你有一個向量所有文件名叫做files

out <- data.frame() 
for (file in files) { 

    # read the file. prepend a path before this step if necessary 
    data <- read.csv(file) 

    # determine V4. This assumes that V3 is guaranteed to have a constant difference in any given file 
    # and that the first row is that difference, as in your example data 
    data$V4 <- data$V3[1] 

    data <- data[, c('V1', 'V4')] #note that I switched my first colname to match yours 

    out <- rbind(out, data) 
} 

# Recover V2 and V3 
out$V3 <- cumsum(out$V4) 
out$V2 <- out$V3 - out$V4 + 1 
out[, c('V1', 'V2', 'V3')] 

請注意,您的文件必須是爲了,否則cumsum()不會是正確的。如果文件不是爲了,你可以建立TE out表後,用cumsum()

+0

只是嘗試這樣做,效果很好,然後再重新訂購。你有擴大的建議 - 說我非常爲.csv 20+個別分區上的文件? –

+0

我已經編輯了答案,包括我試圖解決這個問題 – HarlandMason