length

Description

length is a very simple R function that returns the number of elements in an object, usually a vector.

# Create a vector of length 5
my_vector <- c(1,2,3,4,5)

# Calculate the length of my_vector
length(my_vector)
[1] 5


nchar

It’s important to note that unlike Python, length will not work for calculating the length of a string. Take the following example:

vector <- "OH YEAH!"
length(vector)
[1] 1

Our string vector is one object consisting of multiple characters, and since length returns the number of objects, we will get 1. If we use the nchar function, we get what we want:

vector <- "OH YEAH!"
nchar(vector)
[1] 8