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.
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.
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.
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)
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.
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,]
)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With