# How to get and extract the first n rows of an R DataFrame?

In this Data Analysis tutorial we will show you how to extract and display the first (or first N) rows of your R DataFrame.

## Create an example DataFrame

``````#create R vectors
x <- c(seq (11,15))
y <- c (x ^ 2)
z <- c (ppois (x,8))

#Initialize DataFrame
test <- data.frame (x = x, y = y, z = z)``````

Here’s our DataFrame:

## Get the first n rows in R

#### Using bracket notations

``````n=1      # adjust as needed
test[n,]``````

Remember: You can subset an R DataFrame by using the following syntax: your_df[rows, columns]. If you have a background in Python and pandas, that might be confusing. Make sure to add a comma following the row position, otherwise you’ll be selecting R DataFrame columns not rows.

``````n=1      # adjust as needed

Both methods will render the following result:

```x   y        z
1 11 121 0.888076```

#### Using dplyr to get first n rows

We will now go ahead and explain how to use dplyr slice function to subset our DataFrame rows. In this example we’ll slice the first two rows of our data.

``````library(dplyr)
test %>% slice(seq(n))``````

Alternatively:

``````library(dplyr)
n=2
first_rows  = slice(test,seq(n))
print (first_rows)``````

Both will render this DataFrame:

``` x   y         z
1 11 121 0.8880760
2 12 144 0.9362028```

## Converting the first row to a vector

Once extracted, we can easily convert the DataFrame first row to a vector.

``````n=1
`  11.000000 121.000000   0.888076`
``````library(dplyr)