[R] Randomly extract rows from a data frame

Marc Schwartz marc_schwartz at comcast.net
Mon Feb 19 04:16:42 CET 2007


On Mon, 2007-02-19 at 16:10 +1300, Amy Whitehead wrote:
> Hi,
> 
> I am looking for a way to randomly extract a specified number of rows from a
> data frame.  I was planning on binding a column of random numbers to the
> data frame and then sorting the data frame using this bound column.  But I
> can't figure out how to use this column to sort the entire data frame so
> that the content of the rows remains together.  Does anyone know how I can
> do this?  Hints for other ways to approach this problem would also be
> appreciated.
> 
> Cheers
> Amy

See ?sample

Using the 'iris' dataset in R:

# Select 2 random rows

> iris[sample(nrow(iris), 2), ]
   Sepal.Length Sepal.Width Petal.Length Petal.Width    Species
96          5.7         3.0          4.2         1.2 versicolor
17          5.4         3.9          1.3         0.4     setosa



# Select 5 random rows

> iris[sample(nrow(iris), 5), ]
   Sepal.Length Sepal.Width Petal.Length Petal.Width    Species
83          5.8         2.7          3.9         1.2 versicolor
12          4.8         3.4          1.6         0.2     setosa
63          6.0         2.2          4.0         1.0 versicolor
80          5.7         2.6          3.5         1.0 versicolor
49          5.3         3.7          1.5         0.2     setosa



HTH,

Marc Schwartz



More information about the R-help mailing list