R Programming: Get the length of the first two vectors of a list
Write a R program to get the length of the first two vectors of a given list.
Sample list: (g1 = 1:10, g2 = "R Programming", g3 = "HTML")
Sample Solution :
R Programming Code :
# Create a list with three elements
list1 = list(g1 = 1:10, g2 = "R Programming", g3 = "HTML")
# Print a message indicating that the original list will be shown
print("Original list:")
# Print the contents of the original list
print(list1)
# Print a message indicating that the length of 'g1' and 'g2' will be shown
print("Length of the vector 'g1' and 'g2' of the said list")
# Print the length of the first vector in the list
print(length(list1$g1))
# Print the length of the second vector in the list
print(length(list1$g2))
Output:
[1] "Original list:" $g1 [1] 1 2 3 4 5 6 7 8 9 10 $g2 [1] "R Programming" $g3 [1] "HTML" [1] "Length of the vector 'g1' and 'g2' of the said list" [1] 10 [1] 1
Explanation:
- Create a List: list1 = list(g1 = 1:10, g2 = "R Programming", g3 = "HTML") creates a list named list1 with three elements: g1 (a vector of integers from 1 to 10), g2 (a character string "R Programming"), and g3 (a character string "HTML").
- Print Original List: print("Original list:") followed by print(list1) displays the message "Original list:" and then prints the contents of list1.
- Print Lengths of Vectors: print("Length of the vector 'g1' and 'g2' of the said list") is followed by print(length(list1$g1)) and print(length(list1$g2)) to show the lengths of the vectors g1 and g2. list1$g1 has a length of 10, and list1$g2 has a length of 1.
R Programming Code Editor:
Have another way to solve this solution? Contribute your code (and comments) through Disqus.
Previous: Write a R program to assign new names "a", "b" and "c" to the elements of a given list.
Next: Write a R program to find all elements of a given list that are not in another given list.
Test your Programming skills with w3resource's quiz.
What is the difficulty level of this exercise?
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics