Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I select a sample of rows at random with repetition from a matrix in R?

Tags:

How do I select a sample of rows at random with repetition from a matrix in R?

So do be clear, I would start with a matrix of, for example, 100 rows and I would be able to select 5 of those rows and make a new matrix. I would want the option of doing this either with or without replacement.

like image 977
Henry B. Avatar asked Oct 18 '11 11:10

Henry B.


People also ask

How do I randomly select rows in R?

Method 1: Using Sample_n() function Sample_n() function is used to select n random rows from a dataframe in R. This is one of the widely used functions of the R programming language as this function is used to test the various user build models for prediction and for accuracy purposes.

How do you get a sample from a matrix in R?

To take a random sample from a matrix in R, we can simply use sample function and if the sample size is larger than the number of elements in the matrix replace=TRUE argument will be used.

How do you generate a random sample in R?

For example if we want to generate random numbers from 3 to 10 and we want to generate random numbers 8 times that is 8 results, then we can make use of predefined sample() function in R as follows, > sample(3:10, 8, replace = TRUE)

How do you take a random sample of a Dataframe in R?

Take Random Samples from a Data Frame in R Programming – sample_n() Function. sample_n() function in R Language is used to take random sample specimens from a data frame.


1 Answers

Use sample on the rows with replace=TRUE or replace=FALSE.

If X is your original matrix then

X[sample(nrow(X),size=5,replace=TRUE),] 

or

X[sample(nrow(X),size=5,replace=FALSE),] 

should work. (It may be more readable if you choose the sample first: s <- sample(...) and then subset: newmat <- X[s,])

like image 130
Ben Bolker Avatar answered Sep 21 '22 13:09

Ben Bolker