To count the number of rows in R, you can use the “nrow()” function.
Example 1: Counting the total number of rows
df <- data.frame(
col1 = c(1, 2, 3),
col2 = c(4, 5, 6),
col3 = c(7, 8, 9)
)
nrow(df)
Output
[1] 3
Example 2: Counting rows, excluding rows with NA values
To count the number of rows in a data frame that has no missing values (for example. No NA values) in any of the columns, use the na.omit() function in combination with the nrow() function.
df <- data.frame(
col1 = c(1, 2, 3),
col2 = c(4, NA, 6),
col3 = c(7, 8, NA)
)
df
cat("----Counting rows while excluding rows with NA values----", "\n")
nrow(na.omit(df))
Output
Example 3: Counting rows while excluding NA Values in a specific column
df <- data.frame(
col1 = c(1, 2, 3),
col2 = c(4, NA, NA),
col3 = c(7, 8, 9)
)
nrow(df[!is.na(df$col2), ])
Output
[1] 1
That’s it!
Krunal Lathiya is a seasoned Computer Science expert with over eight years in the tech industry. He boasts deep knowledge in Data Science and Machine Learning. Versed in Python, JavaScript, PHP, R, and Golang. Skilled in frameworks like Angular and React and platforms such as Node.js. His expertise spans both front-end and back-end development. His proficiency in the Python language stands as a testament to his versatility and commitment to the craft.