To count the number of elements in list in R, you can use length() function or length() function. The length() function gives count of number of elements in list and lengths() function gives count of number of elements in each component of list.
The following methods show how you can do it with syntax.
Method 1: Use length() Function
length(list)
Method 2: Use lengths() Function
lengths(list)
The following examples show how to count number of elements in list.
Count Number of Elements in List Using length() Function
Let’s see how we can count number of elements in list:
# Create list
lst <- list(Machine_name=c("A","B","C","D","E","F","G","H","A","B","A","C","D","B","E","H"),
Pressure=c(12.39,11.25,12.15,13.48,13.78,12.89,12.21,12.58,9.6,8.85,7.89,10.24,12.36,11.45,9.47,8.12),
Status=c("OK","Suspect","OK","OK","Suspect","Suspect","Suspect","OK","OK","OK","OK","OK","Suspect","Suspect","Suspect","OK"))
# Count elements
length(lst)
Output:
[1] 3
Here the output shows 3 which means in list there are 3 elements.
Count Number of Elements in List Using lengths() Function
Let’s see how we can get number of elements in each component of list:
# Create list
lst <- list(Machine_name=c("A","B","C","D","E","F","G","H","A","B","A","C","D","B","E","H"),
Pressure=c(12.39,11.25,12.15,13.48,13.78,12.89,12.21,12.58,9.6,8.85,7.89,10.24,12.36,11.45,9.47,8.12),
Status=c("OK","Suspect","OK","OK","Suspect","Suspect","Suspect","OK","OK","OK","OK","OK","Suspect","Suspect","Suspect","OK"))
# Count elements in each component
lengths(lst)
Output:
Machine_name Pressure Status
16 16 16
Here the output shows count of number of elements in each component of list.