6.2 C
London
Thursday, December 19, 2024
HomeRDescriptive Statistics in RHow to Use nrow Function in R (With Examples)

How to Use nrow Function in R (With Examples)

Related stories

Learn About Opening an Automobile Repair Shop in India

Starting a car repair shop is quite a good...

Unlocking the Power: Embracing the Benefits of Tax-Free Investing

  Unlocking the Power: Embracing the Benefits of Tax-Free Investing For...

Income Splitting in Canada for 2023

  Income Splitting in Canada for 2023 The federal government’s expanded...

Can I Deduct Home Office Expenses on my Tax Return 2023?

Can I Deduct Home Office Expenses on my Tax...

Canadian Tax – Personal Tax Deadline 2022

  Canadian Tax – Personal Tax Deadline 2022 Resources and Tools...

You can use the nrow() function in R to count the number of rows in a data frame:

#count number of rows in data frame
nrow(df) 

The following examples show how to use this function in practice with the following data frame:

#create data frame
df frame(x=c(1, 2, 3, 3, 5, NA),
                 y=c(8, 14, NA, 25, 29, NA)) 

#view data frame
df

   x  y
1  1  8
2  2 14
3  3 NA
4  3 25
5  5 29
6 NA NA

Example 1: Count Rows in Data Frame

The following code shows how to count the total number of rows in the data frame:

#count total rows in data frame
nrow(df)

[1] 6

There are 6 total rows.

Example 2: Count Rows with Condition in Data Frame

The following code shows how to count the number of rows where the value in the ‘x’ column is greater than 3 and is not blank:

#count total rows in data frame where 'x' is greater than 3 and not blank
nrow(df[df$x>3 & !is.na(df$x), ])

[1] 1

There is 1 row in the data frame that satisfies this condition.

Example 3: Count Rows with no Missing Values

The following code shows how to use the complete.cases() function to count the number of rows with no missing values in the data frame:

#count total rows in data frame with no missing values in any column
nrow(df[complete.cases(df), ])

[1] 4

There are 4 rows with no missing values in the data frame.

Example 4: Count Rows with Missing Values in Specific Column

The following code shows how to use the is.na() function to count the number of rows that have a missing value in the ‘y’ column specifically:

#count total rows in with missing value in 'y' column
nrow(df[is.na(df$y), ])

[1] 2

There are 2 rows with missing values in the ‘y’ column.

Additional Resources

How to Use rowSums() Function in R
How to Apply Function to Each Row in Data Frame in R
How to Remove Rows from Data Frame in R Based on Condition

Subscribe

- Never miss a story with notifications

- Gain full access to our premium content

- Browse free from up to 5 devices at once

Latest stories