2017-08-24 67 views
0

我有一個3000行和50000列的表。從這些數據中,我想使5個數據集包含原始數據的10%而沒有任何重疊(在這種情況下,3000 = 300的10%)。另外我想要從原始數據集中刪除重採樣數據集。實施例沒有任何重疊的隨機重新採樣

1.Original data (O) 
a. Randomly resampled dataset1 (RD1) 
b. Randomly resampled dataset2 (RD2) 
c. Randomly resampled dataset3 (RD3) 
d. Randomly resampled dataset4 (RD4) 
e. Randomly resampled dataset5 (RD5) 
2. remove RD from O 
a. O - RD1 = New dataset1 
b. O - RD2 = New dataset2 
c. O - RD3 = New dataset3 
d. O - RD4 = New dataset4 
e. O - RD5 = New dataset5 

我嘗試隨機重新採樣如下面中的R

original=read.table("table1.txt", header=F) 
RD1=original[sample(nrow(original), replace=F, size=0.1*nrow(original)), ] 

但它有重疊。我如何製作非重疊套餐?以及如何從原始設置中刪除RD以創建新的數據集?任何awk,sed,python或R解決方案?

+0

也許你應該試試這個'RD1 =原[樣品(1:nrow(原件),取代= F,大小= 0.1 * nrow(original)),]' –

+0

['modelr'](https://github.com/tidyverse/modelr)使這個非常簡單。 – alistaire

+0

或者使用'split(樣本(20),seq(20/5))'和'lapply'(帶有負索引來獲得集合的其餘部分)的子集來創建索引列表。 – alistaire

回答

0

你可以只洗牌線,或隨機指數包含的線陣列組成的數組,如果你不想改變原有的數據,然後做什麼是你想用做前5套300行,並將其從剩下的內容中刪除。

例如使用30線(編號1-> 30),而不是3000輸入:

$ cat tst.awk 
function shuf(array, i, j, t) { 
    # Shuffles an array indexed by numbers from 1 to its length 
    # Copied from https://www.rosettacode.org/wiki/Knuth_shuffle#AWK 
    for (i=length(array); i > 1; i--) { 
     # j = random integer from 1 to i 
     j = int(i * rand()) + 1 

     # swap array[i], array[j] 
     t = array[i] 
     array[i] = array[j] 
     array[j] = t 
    } 
} 

{ arr[NR] = $0 } 

END { 
    srand() 
    shuf(arr) 
    numBlocks = 5 
    pct10 = length(arr) * 0.1 
    for (i=1; i<=numBlocks; i++) { 
     print "------- Block", i 
     for (j=1; j<=pct10; j++) { 
      print ++c, arr[c] 
      delete arr[c] 
     } 
    } 
    print "\n------- Remaining" 
    for (i in arr) { 
     print i, arr[i] 
    } 
} 

$ seq 30 | awk -f tst.awk 
------- Block 1 
1 24 
2 27 
3 28 
------- Block 2 
4 11 
5 16 
6 19 
------- Block 3 
7 2 
8 5 
9 25 
------- Block 4 
10 18 
11 22 
12 15 
------- Block 5 
13 20 
14 10 
15 14 

------- Remaining 
16 12 
17 17 
18 1 
19 8 
20 23 
21 21 
22 9 
23 30 
24 7 
25 29 
26 6 
27 26 
28 13 
29 3 
30 4 

,並再次表明,輸出是隨機的:

$ seq 30 | awk -f tst.awk 
------- Block 1 
1 17 
2 15 
3 22 
------- Block 2 
4 19 
5 1 
6 13 
------- Block 3 
7 7 
8 10 
9 28 
------- Block 4 
10 5 
11 2 
12 8 
------- Block 5 
13 16 
14 11 
15 30 

------- Remaining 
16 14 
17 18 
18 26 
19 4 
20 29 
21 12 
22 21 
23 27 
24 3 
25 24 
26 6 
27 9 
28 23 
29 20 
30 25 
1
# Reproducible data  
data <- mtcars 
n <- nrow(data) 
K <- 5 
# Get indices for splitting 
ind <- integer(n) 
new <- rep(1:K, each = 0.1 * n) 
ind[sample(n, size = length(new))] <- new 
# Split data 
split(data, ind)