簡體   English   中英

隨機重采樣,無任何重疊

[英]Random re-sampling without any overlaps

我有一個3000行和50,000列的表。 我想根據此數據制作5個數據集,這些數據集包含原始數據的10%,沒有任何重疊(在這種情況下,3000的10%= 300)。 我也想從原始數據集中刪除重新采樣的數據集。

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解決方案?

# 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)

如果您不想更改原始數據,則可以只對行進行混排,也可以將索引的數組混排到包含行的數組中,然后對前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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM