0

我有一个矩阵(200x3),我想将它分成 3 个随机选择的不相交集。我怎么能意识到它?

我试图通过示例方法来做到这一点,但示例方法只接受向量,输出并不是我矩阵的一部分。

因此,这是我的矩阵:

          X1           X2     Y
1   -3.381342627  1.037658397 0
2    3.329754336  1.964180648 0
3    1.760001645 -3.414310545 0
4   -2.450315854 -2.299838395 0
5   -3.334593596  0.069458604 0
6    1.708921101 -2.333932571 0
7   -2.650506645  0.348985289 0
8   -2.935307106 -0.402072990 0
9    2.867566309 -3.217712074 0
10   3.617603017  1.956535384 0

我想像这样分成3组:(行号必须是随机选择的)。我希望能够给出集合的大小。例如在这种情况下,4 4 2。

9    2.867566309 -3.217712074 0
3    1.760001645 -3.414310545 0
1   -3.381342627  1.037658397 0
2    3.329754336  1.964180648 0


5   -3.334593596  0.069458604 0
8   -2.935307106 -0.402072990 0
4   -2.450315854 -2.299838395 0
6    1.708921101 -2.333932571 0


10   3.617603017  1.956535384 0
7   -2.650506645  0.348985289 0
4

3 回答 3

3

这是一种方法,

# a matrix with 3 columns
m <- matrix(runif(300), ncol=3)

# split into a list of dataframes (of course, you can convert back to matrices)
m_split <- split(as.data.frame(m), sample(1:3, size=nrow(m), replace=TRUE))

# count nr of rows
sapply(m_split, nrow)

# Or, as in the comment below, split by given number of rows per split
nsplit <- c(30,30,40)
m_split2 <- split(as.data.frame(m), rep(1:3, nsplit))
于 2013-08-14T03:41:12.143 回答
0

我已经解决了它(可能不是最好的方法,但解决了)如下:

nsamples= nrow(data)
//first take a random numbers; %40 of total number of samples
sampleInd = sample(nsamples,0.4*nsamples)
//construct first set via the half of taken indexes
valInd = sampleInd[1:floor(length(sampleInd)/2)]
valSet = dat[valInd,]
//other half
testInd = sampleInd[(floor(length(sampleInd)/2)+1):length(sampleInd)]
testSet = dat[testInd,]
//unused %60
trainSet = dat[-sampleInd,]
ntrain = nrow(trainSet)

可以根据需要更改 Procents。因此,这个想法是通过函数样本在索引方面划分矩阵。然后使用索引来获取实际的矩阵。

于 2013-08-14T04:25:09.440 回答
0

我在评论中提到的想法:

# shuffle rows
rows = sample(nrow(m))

# split any way you like, e.g. 4/4/rest
rows.split = split(rows, c(rep(1,4), rep(2,4), rep(3,nrow(m) - 4 - 4)))

# subset the matrix
lapply(rows.split, function(x) m[x,])
于 2013-08-15T18:32:33.800 回答