[R] Random subset

Marc Schwartz marc_schwartz at comcast.net
Wed Jul 30 20:28:59 CEST 2008


on 07/30/2008 01:18 PM Alessandro wrote:
> Hi all,
>  
> I wish to do a random subset (i.e. 200 or 300 points) from a dataset, but I
> don't find the right code in R.


See ?sample.

Randomly select 10 elements from a 30 element vector:

Vec <- 1:30

 > sample(Vec, 10)
  [1] 16  5 10 29 27 30 21  1 12 28


Randomly select 5 rows from a 10 row matrix:

MAT <- matrix(1:20, 10, 2)

 > MAT
       [,1] [,2]
  [1,]    1   11
  [2,]    2   12
  [3,]    3   13
  [4,]    4   14
  [5,]    5   15
  [6,]    6   16
  [7,]    7   17
  [8,]    8   18
  [9,]    9   19
[10,]   10   20


 > MAT[sample(5), ]
      [,1] [,2]
[1,]    5   15
[2,]    3   13
[3,]    4   14
[4,]    1   11
[5,]    2   12


HTH,

Marc Schwartz



More information about the R-help mailing list