w3resource

R Programming - Count Number of Objects in a given list

R Programming: List Exercise-11 with Solution

Write a R program to count number of objects in a given list.

Sample Solution :

R Programming Code :

# Create a list with various elements: a vector, a matrix, and another list
list_data <- list(c("Red", "Green", "Black"), matrix(c(1, 3, 5, 7, 9, 11), nrow = 2),
                  list("Python", "PHP", "Java"))

# Print a message indicating that the following output is the list
print("List:")

# Print the content of the list
print(list_data)

# Print a message indicating that the following output is the number of objects in the list
print("Number of objects in the said list:")

# Calculate and print the number of objects (elements) in the list
length(list_data)

Output:

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

[[2]]
     [,1] [,2] [,3]
[1,]    1    5    9
[2,]    3    7   11

[[3]]
[[3]][[1]]
[1] "Python"

[[3]][[2]]
[1] "PHP"

[[3]][[3]]
[1] "Java"


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

Explanation:

  • Create a list:
    • list_data <- list(c("Red", "Green", "Black"), matrix(c(1, 3, 5, 7, 9, 11), nrow = 2), list("Python", "PHP", "Java"))
      • This line creates a list named list_data containing:
        • A vector with three strings: "Red", "Green", "Black"
        • A matrix with the numbers 1, 3, 5, 7, 9, 11 arranged in 2 rows
        • Another list with three strings: "Python", "PHP", "Java"
  • Print the label for the list:
    • print("List:")
      • This line prints the label "List:" to indicate that the following output will display the contents of list_data.
  • Print the list:
    • print(list_data)
      • This line prints the actual contents of list_data.
  • Print the label for the number of objects:
    • print("Number of objects in the said list:")
      • This line prints the label "Number of objects in the said list:" to indicate that the following output will show the count of items in list_data.
  • Print the number of objects in the list:
    • length(list_data)
      • This line calculates and prints the number of objects (elements) in list_data, which is 3 in this case.

R Programming Code Editor:



Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous: Write a R program to create a list of dataframes and access each of those data frames from the list.
Next: Write a R program to convert a given dataframe to a list by rows.

Test your Programming skills with w3resource's quiz.

What is the difficulty level of this exercise?



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://www.w3resource.com/r-programming-exercises/list/r-programming-list-exercise-11.php