# R Program to extract first two rows from a given data frame

April 22, 2022, Learn eTutorial
1596

## How to extract the first two rows from a given data frame?

To write an R program for taking rows from a given data frame, first, we are using data.frame() function which is a built-in function for creating the data frame. A data frame is a list of equal-length vectors, used to store different types of data like numeric, string, etc in a table format with rows and columns. then we get the needed rows by calling the row numbers of that data frame.

## How to extract the first two rows from a given data frame in the R program

In this R program, we are using variables L, E, A, R, and N for holding different types of vectors. Then call the data.frame() function for creating a data frame. Finally, extract the first two rows by calling like L[1:2,].

## ALGORITHM

STEP 1: Assign variables L,E,A,R,N with vector values

STEP 2: First print the original vector values

STEP 3: Extract the first two rows from a given data frame as L[1:2,]

STEP 4: Assign variable result with the result of data.frame function

STEP 5: print the variable result which holds the result

## R Source Code

```                                          ```L = data.frame
(
E = c('Jhon', 'Hari', 'Anu', 'Jack', 'Disna'),
A = c(10, 9.5, 12.2, 11, 8),
R = c(2, 1, 2, 4, 1),
N = c('yes', 'no', 'yes', 'no', 'no')
)
print("Original dataframe:")
print(L)
print("Extract first two rows:")
result =  L[1:2,]
print(result)```
```

## OUTPUT

```[1] "Original dataframe:"
name    score attempts qualify
1  John       10        2     yes
2  Hari      9.5       1     no
3  Anu    12.2      2     yes
4  Jack      11        4     no
5  Disna      8         1     no

[1] "Extract first two rows:"
name     score      attempts     qualify
1       John      10           2           yes
2       Hari     9.5          1           no
```

VIEW ALL
VIEW ALL