The length() function is used to find the length of list,vector or data frame.

The following method shows how you can do it with syntax.

Method: Use length() Function


The following examples show how to use length() function in R.

Use length() Function to Find Length of Vector

Suppose we want to find length of vector using length() function:

# Define vector
vector1 <-c(45,85,89,78,12,36,68,32,12)

# Find length
len <- length(vector1)

# Show length


[1] 9

As we can see in output the length of vector vector1 is 9.

Use length() Function to Find Length of Data Frame

Let’s see how we can calculate length data frame using length() function:

# Create data frame
df <- data.frame(Machine_name=c("A","B","C","D","E","F"),
                 Pressure=c(78.2, 71.7, 80.21, 83.12, 82.56, 79.50),
                 Temperature=c(31, 35, 36, 36, 38, 32),

# Get length of data frame
l <-length(df)

# Print length


[1] 4

As output we can see length() function returns the number of columns which is 4.

The length() function count the elements from vector,list or data frame and return the total.