- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- 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.
Example
> 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
- Related Articles
- 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 subset rows of data frame without NA using dplyr in R?
- How to split a data frame in R into multiple parts randomly?
- 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?
- Remove rows from a data frame that exists in another data frame in R.
- 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?
- How to create a clone of a data frame in R without data values?
- How to remove empty rows from an R data frame?
- How to create a new data frame for the mean of rows of some columns from an R data frame?
- How to plot rows of a data frame as lines in R?

Advertisements