R Program to count number of objects in a given list

How to count the number of objects in a given list

Here we explain how to write an R program to count the number of objects in a given list. Here we are using a built-in function length() for this. This function helps to get or set the length of vectors (including lists), factors, and any other R object. The syntax of this function is

length(x) <- value

– where x is an R object for replacement, a vector or factor and value is a non-negative integer or double.

How to count the number of objects in a given list in the R program

Below are the steps used in the R program to count the number of objects in a given list. In this R program, we directly give the values to a built-in function length(). Here we are using the variable Ldata for holding the list elements of different types. Call the function length() for finding the length of the list elements.Consider variables vec1,vce2 for holding converted vector values. Finally, add these two vectors and assigned them to variable V.And print the final vector.

ALGORITHM

  • STEP 1: Assign variable Ldata with a lists
  • STEP 2: Print the original list
  • STEP 3:Find the length of the list by calling the function length() as length(Ldata)
  • STEP 4: Print the length of the list

R Source Code

Ldata <- list(c("Blue","Green","Red"), 
              matrix(c(2,3,6,7,8,9), nrow = 2),
              list("Java", "PHP", "C")
             )

print("List:")
## [1] "List:"
print(Ldata)
## [[1]]
## [1] "Blue"  "Green" "Red"  
## 
## [[2]]
##      [,1] [,2] [,3]
## [1,]    2    6    8
## [2,]    3    7    9
## 
## [[3]]
## [[3]][[1]]
## [1] "Java"
## 
## [[3]][[2]]
## [1] "PHP"
## 
## [[3]][[3]]
## [1] "C"
print("Number of objects in the list:")
## [1] "Number of objects in the list:"
length(Ldata)
## [1] 3