The** nrow()** function in **R** is **“used to get the rows for an object“**. The

**nrow()**function can easily extract the number of rows in an object that can be a matrix, data frame, or even a dataset.

**Syntax**

`nrow(data)`

**Parameters**

The data is a required argument that can be **vector, array, data frame, NULL, or matrix.**

**Return value**

It returns the number of rows of an input R object.

**Example 1: Counting the number of rows in the Data Frame**

Create a data frame using the **data.frame()** function.

Use the **nrow()** function to count the number of rows in a **data frame**.

```
df <- data.frame(
students = c("Michael", "Taylor", "Selena"),
marks = c(90, 80, 75),
levels = c(10, 7, 8)
)
nrow(df)
```

**Output**

`[1] 3`

Our data frame has three rows and three columns, and we get the three rows using the **nrow()** function.

**Example 2: Counting the number of rows of the matrix in R**

To **count** the **number** of **rows** of a **matrix** in** R**, use the **nrow()** function.

```
mat <- matrix(1:9, 3, 3)
print(mat)
cat("---Couting number of rows of a matrix---", "\n")
nrow(mat)
```

**Output**

```
[,1] [,2] [,3]
[1,] 1 4 7
[2,] 2 5 8
[3,] 3 6 9
---Couting number of rows of a matrix---
[1] 3
```

You can see that the **nrow()** function returns three as output because the **matrix** has **three** **rows**.

**Example 3: Counting the number of rows of an array in R**

Use the **nrow()** function to count the number of rows of an array in R.

```
arr <- array(1:12, dim = 4:3)
print(arr)
cat("---Counting number of rows using nrow() function---", "\n")
nrow(arr)
```

**Output**

```
[,1] [,2] [,3]
[1,] 1 5 9
[2,] 2 6 10
[3,] 3 7 11
[4,] 4 8 12
---Counting number of rows using nrow() function---
[1] 4
```

You can see that the array has four rows and three columns, and its output is the same.

**Example 4: nrow() function with a condition in R**

To use the **nrow()** function **with** **a** **condition** in **R,** use the **subsetting.**

The subsetting approach helps us filter some data based on the condition.

```
df <- data.frame(LETTERS, letters, position = 1:length(letters))
dfSubset <- df[6:10, ]
nrow(dfSubset)
```

**Output**

`[1] 5`

Let’s use the **iris dataset **and apply a condition while fetching the number of rows of the data frame.

`nrow(iris[iris$Sepal.Length > 3, ])`

**Output**

`[1] 150`

You can see that the iris dataset has 150 rows whose **Sepal.Length** is greater than 3.

Krunal Lathiya is a Software Engineer with over eight years of experience. He has developed a strong foundation in computer science principles and a passion for problem-solving. In addition, Krunal has excellent knowledge of Data Science and Machine Learning, and he is an expert in R Language.