Home » How to Find the Size of a Data Frame in R

How to Find the Size of a Data Frame in R

by Tutor Aspire

You can use the following functions in R to display the size of a given data frame:

  • nrow: Display number of rows in data frame
  • ncol: Display number of columns in data frame
  • dim: Display dimensions (rows and columns) of data frame

The following examples show how to use each of these functions in practice with the following data frame:

#create data frame
df frame(team=c('A', 'B', 'C', 'D', 'E', 'F'),
                 points=c(99, 90, 86, 88, 95, 99),
                 assists=c(33, 28, 31, 39, 34, 25),
                 rebounds=c(12, NA, 24, 24, 28, 33))

#view data frame
df

  team points assists rebounds
1    A     99      33       12
2    B     90      28       NA
3    C     86      31       24
4    D     88      39       24
5    E     95      34       28
6    F     99      25       33

Example 1: Use nrow() to Display Number of Rows

The following code shows how to use the nrow() function to display the total number of rows in the data frame:

#display total number of rows in data frame
nrow(df)

[1] 6

There are 6 total rows.

Note that we can also use the complete.cases() function to display the total number of rows with no NA values:

#display total number of rows in data frame with no NA values
nrow(df[complete.cases(df), ])

[1] 5

There are 5 total rows that have no NA values.

Example 2: Use ncol() to Display Number of Columns

The following code shows how to use the ncol() function to display the total number of columns in the data frame:

#display total number of columns in data frame
ncol(df)

[1] 4

There are 4 total columns.

Example 3: Use dim() to Display Dimensions

The following code shows how to use the dim() function to display the dimensions (rows and columns) of the data frame:

#display dimensions of data frame
dim(df)

[1] 6 4

This tells us there are 6 rows and 4 columns in the data frame.

You can also use brackets with the dim() function to display only the rows or columns:

#display number of rows of data frame
dim(df)[1]

[1] 6

#display number of columns of data frame
dim(df)[2]

[1] 4

Additional Resources

The following tutorials explain how to perform other common tasks in R:

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

You may also like