 # R Program to how to select some random rows from a given data frame

November 20, 2021, Learn eTutorial
1058

## How to select some random rows from a given data frame

Here we are explaining how to write an R program to select some random rows from a given data frame. Here we are using a built-in functions data.frame(),nrow(). A data frame is used for storing data tables which has a list of vectors with equal length. The data frames are created by function data.frame(), which has tightly coupled collections of variables. And the method nrow() returns the number of rows present in x The syntax of this function is,

``````
nrow(x)
```
```

Where x indicates the a vector, array, data frame, or NULL.

## How to select some random rows from a given data frame in the R program

Below are the steps used in the R program to change a column name of a given data frame. In this R program, we directly give the data frame to a built-in function. Here we are using variables E, N, S, A, Q for holding different types of vectors. Call the function data.frame() for creating data frame. Finally, select the random rows by calling the method nrow() like E[sample(nrow(E), 3),]

## ALGORITHM

STEP 1: Assign variables E,N,S,A,Q with vector values

STEP 2: First print original vector values

STEP 3: Select the random rows by calling E[sample(nrow(E), 3),]

STEP 4: Print the final data frame

## R Source Code

```                                          ```E = data.frame(
N = c('Jhon', 'Hialy', 'Albert', 'James', 'Delma'),
S = c(10, 9.5, 12.2, 11, 8),
A = c(2, 1, 2, 4, 1),
Q = c('yes', 'no', 'yes', 'no', 'no')
)
print("Original data frame:")
print(E)
print("Select three random rows of the data frame:")
print(E[sample(nrow(E), 3),])```
```

## OUTPUT

``` "Original data frame:"
N    S A   Q
1   Jhon 10.0 2 yes
2  Hialy  9.5 1  no
3 Albert 12.2 2 yes
4  James 11.0 4  no
5  Delma  8.0 1  no
 "Select three random rows of the data frame:"
N    S A   Q
4  James 11.0 4  no
5  Delma  8.0 1  no
3 Albert 12.2 2 yes```