- Trending Categories
- Data Structure
- Operating System
- C Programming
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to randomly select a fixed number of rows without replacement from a data frame in R?
This can be done simply by using sample function.
> df = data.frame(matrix(rnorm(20), nrow=5)) > df X1 X2 X3 X4 1 -0.3277833 -0.1810403 0.2844406 -2.9676440 2 0.8262923 0.4334449 0.4031084 -1.9278049 3 -0.1769219 -0.1583660 -0.2829540 -0.1962654 4 1.0357773 0.9326049 0.3250011 -1.8835882 5 -1.0682642 -0.6589731 -0.4783144 -0.2945062
Let’s say we want to select 3 rows randomly then it can be done as follows −
> df[sample(nrow(df), 3), ] X1 X2 X3 X4 2 0.8262923 0.4334449 0.4031084 -1.9278049 1 -0.3277833 -0.1810403 0.2844406 -2.9676440 5 -1.0682642 -0.6589731 -0.4783144 -0.2945062
- How to create an empty data frame with fixed number of rows and without columns in R?
- How to randomly sample rows from an R data frame using sample_n?
- How to select rows of a data frame that are not in other data frame in R?
- How to create a data frame in R with repeated rows by a sequence of number of times or by a fixed number of times?
- How to split a data frame in R into multiple parts randomly?
- How to subset rows of data frame without NA using dplyr in R?
- Remove rows from a data frame that exists in another data frame in R.
- How to create a clone of a data frame in R without data values?
- Randomly SELECT distinct rows in a MySQL table?
- How to select rows based on range of values of a column in an R data frame?
- How to remove rows in R data frame that contains a specific number?
- How to select rows of an R data frame that are non-NA?
- How to divide data frame rows by number of columns in R?
- Select a fixed number of random records from a MySQL table?
- How to create a new data frame for the mean of rows of some columns from an R data frame?