user1813564
user1813564

Reputation: 63

How to delete the conditioned row from matrix in r

so basicly I want to separate a random generated matrix into 2 matrix, 1 for training and 1 for testing.

  a <- s[sample(nrow(s),size=3,replace=FALSE),]  
  b <- s[-a,]

> s
         [,1]        [,2]
 [1,]  0.69779187 -0.75869384
 [2,] -0.46857477 -0.33813598
 [3,]  0.53903809 -0.95950598
 [4,] -0.33312675 -0.49951164
 [5,]  0.88500834  0.08256923
 [6,]  0.63664652  0.87420720
 [7,]  0.61614134  0.77893294
 [8,]  0.36956134  0.07586245
 [9,] -0.03678593 -0.23743987
[10,] -0.27057064 -0.86067063

> a
       [,1]        [,2]
[1,]  0.8850083  0.08256923
[2,]  0.6366465  0.87420720
[3,] -0.2705706 -0.86067063

> b
 [,1] [,2]

The idea here is generate a 10*2 matrix, and random pick 3 rows as training data from matrix, then output the training matrix and the rest row of matrix as testing matrix.

Does anyone has some suggestions on how to delete a from s?

Upvotes: 0

Views: 39

Answers (1)

Artem Sokolov
Artem Sokolov

Reputation: 13691

The issue is that you're trying to index s with a matrix a, rather than the randomly selected indices. Modifying your code to the following should do the trick:

i <- sample(nrow(s),size=3,replace=FALSE)
a <- s[i,]  
b <- s[-i,]    # Note the indexing with i, rather than a

Upvotes: 1

Related Questions