-1

我有一个数据集,我需要将其分成三个不同大小的互斥随机样本。我用了:

testdata<-sample(47959,14388,replace=FALSE,prob=NULL)

尝试创建一个样本(数据集大小为 47959),但我不知道如何将这个样本变成 R 中的可操作数据集。

4

1 回答 1

2

一些数据:

set.seed(42)
x <- sample(20, size=100, replace=TRUE)
head(x)
## [1] 19 19  6 17 13 11

随机尺寸

创建所有 1:3 的索引,并使用它来子集您的数据:

i <- sample(1:3, size=length(x), replace=TRUE)
head(i)
## [1] 2 1 1 2 3 3

现在把它分成三组(有很多方法可以做到这一点):

x.grouped <- split(x, i)
str(x.grouped)
## List of 3
##  $ 1: int [1:31] 19 6 15 20 9 5 8 9 18 20 ...
##  $ 2: int [1:30] 19 17 14 10 6 10 19 3 10 19 ...
##  $ 3: int [1:39] 13 11 15 3 15 19 12 2 8 19 ...

三组的相对大小将随机变化。

受控尺寸

indices表示您希望在每个组中的大小。

indices <- c(20, 50, 30)
indices.cs <- cumsum(indices)
x.unsorted <- sample(x)
xs.grouped.sized <- mapply(function(a,b) x.unsorted[a:b],
    1+lag(indices.cs, default=0),
    indices.cs,
    SIMPLIFY=FALSE)
str(xs.grouped.sized)
## List of 3
##  $ : int [1:20] 2 7 13 1 19 7 14 20 19 1 ...
##  $ : int [1:50] 13 6 19 4 19 20 20 11 17 3 ...
##  $ : int [1:30] 1 10 7 16 9 16 17 11 14 8 ...

编辑:更新的实施

indices <- sample(rep(1:3, times = c(20,50,30)))
str(split(x, indices))
## List of 3
##  $ 1: int [1:20] 6 3 10 6 10 20 17 8 5 13 ...
##  $ 2: int [1:50] 19 19 17 15 14 15 19 20 3 19 ...
##  $ 3: int [1:30] 13 11 15 19 10 12 3 11 14 1 ...
于 2015-03-28T20:30:21.690 回答