0

私は、ランダムに選択された3つのばらばらのセットに分割したいマトリックス(200x3)を持っています。どのように私はそれを実現することができますか?

サンプル メソッドを使用して実行しようとしましたが、サンプル メソッドはベクトルのみを受け入れ、出力は実際にはマトリックスの一部ではありません。

したがって、それは私のマトリックスです:

          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

これが1つの方法です。

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

利益率はお好みで変更可能です。したがって、アイデアは、関数 sample を介してインデックスの観点から行列を分割することです。次に、インデックスを使用して実際の行列を取得します。

于 2013-08-14T04:25:09.440 に答える