R Program to count number of objects in a given list

February 26, 2023, Learn eTutorial

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

For creating 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

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

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. Finally, add these two vectors and assigned them to variable V, and print the final vector.


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("Number of objects in the list:")


[1] "List:"
[1] "Blue"   "Green" "Red"

     [,1] [,2] [,3]
[1,]    2    6    8
[2,]    3    7   9

[1] "Java"

[1] "PHP"

[1] "C"

[1] "Number of objects in the list:"
[1] 3