The difference between length() and lengths() in R programming

Both functions look the same, but each has slightly different purposes

Pierre DeBois
3 min readJan 26, 2024

Most R practitioners know there is a built-in function called length(), which is used to display the number of elements within a data object.

What most don’t realize is that there is a second built-in length function, called lengths(), which provides some nuanced yet important options if you use an object length in a syntax.

Where length() shows the length of an object, lengths() is designed to show the length of each element in a data object.

For example, when I apply length() to this object of 7 numbers, the number of elements is summed and returned. So in this instance, R returns the number 7

The lengths() function returns the count for each observation instead, so we see seven number 1s, a one for each observation instead of the sum value, 7.

So how is lengths() beneficial? The lengths() function returns a vector rather than a summary integer in length, so its values are helpful if there are a series of objects with varying…

--

--

Pierre DeBois

#analytics |#datascience |#JS |#rstats |#marketing services for #smallbiz | #retail | #nonprofits Contrib @CMSWire @smallbiztrends #blackbusiness #BLM