R Program to count number of objects in a given list


February 26, 2023, Learn eTutorial
1219

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.

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

OUTPUT

[1] "List:"
[[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"


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